Let\'s say you have-
struct Person {
char *name;
int age;
int height;
int weight;
};
If you do-
struct Pe
Don't assume that the memory storing the pointer for name is the same as the memory storing the data for name. Assuming a 4 byte word size, you have the following:
char * (4 bytes)
int (4 bytes)
int (4 bytes)
int (4 bytes)
================
total: 16 bytes
which is: sizeof(char*) + sizeof(int) + sizeof(int) + sizeof(int)
. C knows the size because you've told it the size of the elements in the struct definition.
I think what you are confused about is the following:
The contents at the char *
will be a memory location (e.g. 0x00ffbe532
) which is where the actual string will be stored. Don't assume that the struct contents are contiguous (because of the pointer). In fact, you can be pretty sure that they won't be.
So, to reiterate, for an example struct Person
(this is just an example, the locations won't be the same in a real program.)
location : [contents]
0x0000 : [0x00ffbe532]
0x0004 : [10]
0x0008 : [3]
0x000C : [25]
0x00ffbe532 : [I am a string\0]
I think you should also need to allocate memory for the name attribute
The name
member is just a pointer. The size of a pointer varies with the underlying architecture, but is usually 4 or 8 bytes nowadays.
The data that name
can point to (if assigned later) should be laid out in an area that does not coincide with the struct
at all.
At the language level, the struct
doesn't know anything about the memory that the name
member is pointing to; you have to manage that manually.
It doesn't. You have to do that too.
struct Person *who = malloc(sizeof(struct Person));
who->name = malloc(sizeof(char) * 16); /* for a 15+1 character array */