Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

char and pointer in c langage

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading