The first thing to do is to read the warnings from your compiler as they contain valuable information about problems with your code. Compiling the original code with gcc and clang gives these warnings:
clang:
so5.c:12:12: warning: incompatible integer to pointer conversion passing 'int' to parameter of type 'char *' [-Wint-conversion]
gcc:
so5.c:12:12: warning: passing argument 1 of ‘strcpy’ makes pointer from integer without a cast [-Wint-conversion]
strcpy(s1.age, "18");
So the offending line is:
strcpy(s1.age, "18");
is first treating the uninitiated s1.age as pointer and tries to copy the string into this unknown location. This will very likely result in a segmenation fault.
You could of course make a pointer of this and fill its memory contents with the "18"
strcpy(&s1.age, "18");
But wait this results in a print like:
Sammy, 14385
Because the string is encoded in ascii, three bytes 0x31,0x38,0
When written into the location of the int age
field as 0x003831
or in decimal 14385
. This is however pure luck that the reaming byte(s) was randomly initiated to 0.
The correct way to assign age a value is with an assignment:
s1.age = 18;