0

I have a method that returns me a pointer to characters, in the main file when I print I have the complete string, when I look at the length I only have 8 (up to character "c") when I loop over it I only have 8 characters. why when i print "p" i have my whole string and when i loop i only have 8 characters ? can you help me understand because I would like to stock all the characters to process them ?

method :

char* getData(char* file) {
    FILE* f = fopen(file, "r");
    char *string = malloc(250);
    int i = 0;
    if(f) {
        int c;
        printf("\nopen file to get data : %s\n", file);
        while((c = getc(f)) != EOF) {
            string[i] = c;
            i++;
        }
        string[i] = '\0';
        fclose(f);
    } else {
        printf("\nopen file to get data error...\n");
    }
    return string;
};

main file :

char* file = "target/to/message.txt";
char* p;

p = getData(file);
printf("\npointer in main file :\n--%s--\n", p);
printf("\n----------------\n");

printf("\nlen pointer in main file : --%llu--\n",sizeof(p));
printf("\n----------------\n");

for(unsigned long long i=0;i<sizeof(p);i++) {
    printf("\nloop to pointer p : --%c--",p[i]);
}

out of console :

enter image description here

1 Answer 1

1

use strlen() instean of sizeof for char* variables, sizeof() is giving you the address of char* p which is 8 byte long and thus only few characters are getting printed.

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

1 Comment

Actually sizeof(pointer) is 8 byte long on a 64-bit machine and 4 byte long on a 32-bit machine.

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.