1

I am trying to convert a normal C string into a Pascal string. I am running into trouble when I need to assign the first index of the pascal string to be the length of the string. I'll place my code below, but I cannot seem to figure out how to convert the length of the original string (especially when it is over 10), slen, into a char that can then be assigned to an index.

char pascal[slen];
char pascalFirst = slen + '0';  //Having such a hard time assigning pascal[0]
printf("%c\n", pascalFirst);
pascal[0] = pascalFirst;

printf("%s pasFirst\n", pascal);

for (int i =0 ; i < strlen(pascal); i++){
    pascal[i+1] = s[i];

}
printf("%s\n", pascal);
7
  • Why the + '0'? That makes no sense. Commented Sep 14, 2020 at 22:50
  • honestly @tadman I saw somewhere else someone did that so I gave it a try. Commented Sep 14, 2020 at 22:55
  • '0' is the ASCII value of zero (48) and shouldn't be there. Don't go down the road of Cargo Cult Programming. If you see someone do something that's where you need to stop, think, and understand what they're attempting before just mimicking what they did. The Pascal string format requires the first byte to be the length expressed as an unsigned char, not an ASCII value of any kind. Not trying to bust on you here, but C is an extremely unforgiving language and just pasting in arbitrary code can get you into heaps of trouble. Commented Sep 14, 2020 at 22:55
  • He is confusing the fact that the first 'char' of the string is not an ascii value for the length, but is the actual number from 0-255. Easy to do if you don't understand what the first byte actually represents. Commented Sep 14, 2020 at 22:57
  • 1
    I got it. Thanks mates Commented Sep 14, 2020 at 23:10

1 Answer 1

1

It should be a simple as:

char* to_pstr(char* src) {
  char* p = malloc(strlen(src) + 1);

  *((unsigned char*) p) = strlen(src);
  strncpy(src, &p[1], strlen(src));

  return p;
}

Where this of course presumes that src is <= 255 characters long.

Sign up to request clarification or add additional context in comments.

1 Comment

With the reminder that you need to free that string as it has been dynamically allocated.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.