0

Trying to write a simple pascal to cstring conversion method. The method takes a void* ptr to the pascal string. The resulting cstring returns the correct number of characters for the pascal string that gets passed. But all it contains is the hex value for the length of the string. For instance, a pascal strings first element is the length of the string. So if the number in the first element is 15, for instance, the return statement is returning a cstring with 15 characters all set to FF. its as though the pointer isn't being incremented. Not sure how to fix this. Any help would be appreciated.

#include <stdio.h>
#include <stdlib.h>

char* pascal_convert(void* ptr) {
int len = *((int*)ptr)+1;
char *cString = malloc(sizeof(char) * (len));
(int*)ptr + 1;
for (int i = 0; i < len; i++) {
    cString[i] = *((char*)ptr);
    (char*)ptr + 1;
}
cString[len] = '\0';
return cString;

}

3
  • (char*)ptr + 1; should be (char*)ptr ++ ; Commented Oct 24, 2016 at 4:19
  • Adding : what size is your int ? what is your pascal string maximum size ? Commented Oct 24, 2016 at 4:21
  • the the value of the int is the value of the first element in the pascal string. There is no upper bound on the size of the pascal string. incrementing the cast pointer with ++ doesnt work. Commented Oct 24, 2016 at 4:32

1 Answer 1

1

You need to store current address of string somewhere

int currentPtr = (int*)ptr + 1;
for (int i = 0; i < len; i++) {
    cString[i] = *((char*) currentPtr);
    currentPtr++;
}
Sign up to request clarification or add additional context in comments.

2 Comments

This worked. Thank you. Would you mind explaining what I did wrong ?
Your code (char*)ptr + 1; increase the address but ptr value will stay the same.

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.