typedef struct{
char name[30];
char surname[30];
int age;
} data;
defines that data
should be a block of memory that fits 60 chars plus 4 for the int (see note)
[----------------------------,------------------------------,----]
^ this is name ^ this is surname ^ this is age
This allocates the memory on the stack.
data s1;
Assignments just copies numbers, sometimes pointers.
This fails
s1.name = "Paulo";
because the compiler knows that s1.name
is the start of a struct 64 bytes long, and "Paulo"
is a char[] 6 bytes long (6 because of the trailing \0 in C strings)
Thus, trying to assign a pointer to a string into a string.
To copy "Paulo" into the struct at the point name
and "Rossi" into the struct at point surname
.
memcpy(s1.name, "Paulo", 6);
memcpy(s1.surname, "Rossi", 6);
s1.age = 1;
You end up with
[Paulo0----------------------,Rossi0-------------------------,0001]
strcpy
does the same thing but it knows about \0
termination so does not need the length hardcoded.
Alternatively you can define a struct which points to char arrays of any length.
typedef struct {
char *name;
char *surname;
int age;
} data;
This will create
[----,----,----]
This will now work because you are filling the struct with pointers.
s1.name = "Paulo";
s1.surname = "Rossi";
s1.age = 1;
Something like this
[---4,--10,---1]
Where 4 and 10 are pointers.
Note: the ints and pointers can be different sizes, the sizes 4 above are 32bit as an example.