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 :
CodePudding user response:
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.