Let\'s say you have-
struct Person {
char *name;
int age;
int height;
int weight;
};
If you do-
struct Pe
Pointer members occupy one word in my experience (the address on witch the data actually resides) so the size will probably be 16 bytes (assuming one word is 4 bytes)
As the man said above you need to separately allocate memory for *name witch will free memory someplace else for the size you desire
It won't know, You will have to allocate memory for it separately.
struct Person *who = malloc(sizeof(struct Person));
Allocates enough memory to store an object of the type Person
.
Inside an Person
object the member name
just occupies a space equivalent to size of an pointer to char
.
The above malloc
just allocates that much space, to be able to do anything meaningful with the member pointer you will have to allocate memory to it separately.
#define MAX_NAME 124
who->name = malloc(sizeof(char) * MAX_NAME);
Now the member name
points to an dynamic memory of size 124
byte on the heap and it can be used further.
Also, after your usage is done you will need to remember to free
it explicitly or you will end up with a memory leak.
free(who->name);
free(who);
It will allocate 4 bytes for the name
pointer, but no space for the "real" string. If you try to write there you will seg fault; you need to malloc
(and free
) it separately.
Using string
(in C++) can save you some headache
You have a pointer to a name character array in your struct, ie. it will consume that much bytes that are needed to represent a memory address.
If you want to actually use the field, you must allocate additional memory for it.
It allocates memory for the just the pointer to a char. You need to do a separate allocation for the contents.
There are other options although:
If you are OK with having a fixed sized maximum length, you can do:
struct Person {
char name[PERSON_NAME_MAX_LENGTH+1];
int age;
int height;
int weight;
};
And allocate it as in your example.
Or you can declare a variable sized struct, but I wouldn't recommend this as it is tricky and you cannot have more than one variable size array per struct:
struct Person {
int age;
int height;
int weight;
char name[]; /*this must go at the end*/
};
and then allocate it like:
struct Person *who = malloc(sizeof(struct Person) + sizeof(char)*(name_length+1));
For pointers the struct is allocated enough memory just for the pointer. You have to create the memory for the char* and assign the value to the struct. Assuming you had char* name
somewhere:
struct Person *who = malloc(sizeof(struct Person));
who->name = malloc((strlen(name)+1) * sizeof(char));
strcpy(who->name, name)