I have searched on this site the topics about malloc
on structs. However, I have a slightly problem. Is that malloc
on the element of a struct different from malloc
on the whole struct, especially when that struct is quite simple, that is, only a member that is exactly what we all want to allocate? To be clear, see the code corresponding to student
and student2
structs below.
struct student {
int* majorScore;
};
struct student2 {
int majorScore[3];
};
int main()
{
struct student john;
john.majorScore = (int*) malloc(sizeof(int) * 3);
john.majorScore[0] = 50;
john.majorScore[1] = 27;
john.majorScore[2] = 56;
struct student2* amy= (struct student2*)malloc(sizeof(struct student2));
amy->majorScore[0] = 50;
amy->majorScore[1] = 27;
amy->majorScore[2] = 56;
return 0;
}
Are they different in memory level? If yes, what is the difference? If no, which is perhaps better in terms of a good programming style?
malloc
on a stuct will only allocate the size of the struct itself, not the size of dynamic data pointed to by pointers within the struct.john
you allocate the array within a localstruct
. Foramy
you allocate onestruct
on the heap with a fixed array. Which is better? If you don't know how many scores there are at compile time, they can't have a fixed array..heap
section of memory. Which is better in terms of good programming style? Debatable and dependent on your use cases. I would argue amajorScore
array of size 3 isn't realistic for real-world scenarios, but if it suites your needs then it's fine to use this method.student2
contains a 3-elements array ofint
.student
contains anint
pointer. Those are two very different things.malloc()
!