I have a struct member as a char * and assign it to a string literal \"John\" on the struct initialisation as shown below. The string prints fine with printf.
However, i
The commenters are saying that the code you provided does not give enough information to solve your problem. It looks like the error lies elsewhere in your code. I can convert your code to a MCVE like this:
#include
struct person
{
//char name[20];
char* name;
int age;
};
int main(void)
{
struct person p1 = {"John", 25};
printf("%s\n", p1.name);
FILE *fp = fopen("test.txt", "w");
fwrite(p1.name, 1, 10, fp);
fclose(fp);
char buffer[20];
fp = fopen("test.txt", "r");
fread(buffer, 1, 10, fp);
fclose(fp);
printf("The stored name is: %s\n", buffer);
return 0;
}
But I am sure that what you have differs, because this code works:
John
The stored name is: John
From the new code that you provided, I can see that your problem is that you are writing the contents of a struct to a file instead of writing a string to a file, as in your original code example.
The original code used:
fwrite(p1.name, 1, 10, fp);
and wrote 10 bytes of the string p1.name to the file "test.txt" (blowing right past the NUL terminator of the string "John" and saving garbage values that would not be seen on printing the string).
The new code uses:
fwrite(&p1, 1, 10, fp);
saving the first 10 bytes of the struct p1 to the file "test.txt".
When the struct contains char name[20];, the first 10 bytes are chars stored in the character array name, and this is why your code appeared to work in this case.
When the struct instead contains char *name;, the first few bytes saved belong to the pointer name(8 bytes on my system), not to the string literal "John". The next few bytes belong to the int age(4 bytes on my system). It is these values and not the chars of the string literal "John" that are being saved in this case.
Note that the sizes of pointers and ints may be different on different systems, and it is entirely possible to have 4 bytes for the pointer and 4 bytes for the int, leaving 2 bytes which are saved that are not part of the struct. Also, though this does not affect you here, there may be padding after the first member of the struct.