Reputation: 129
I came across something I don't understand why and I'd like to hear an explanation about it. I have this struct:
typedef struct Student {
int age;
char *name;
} Student;
int main()
{
Student **test1 = calloc(2, sizeof(*test1));
Student **test2 = calloc(2, sizeof(**test2));
return 0;
}
I've noticed that test1 gets 2 memory allocations (as it should) while test2 gets 4. Why is that and which is the correct usage? I assume its the first one but i'm not sure why.
Thanks!
Upvotes: 0
Views: 136
Reputation: 67751
sizeof(*test)
is a size in bytes of the pointer to Student
. It will be on most systems 4 or 8.
sizeof(**test)
gives you the size of the Student
. The allocation (test2) makes no sense at all.
You can easily test it yourself by printing the sizes:
#include <stdio.h>
#include <malloc.h>
typedef struct Student {
int age;
char *name;
double somedata[100];
} Student;
int main()
{
Student **test1;
Student **test2;
printf("%zu\n", sizeof(*test1));
printf("%zu\n", sizeof(**test2));
return 0;
}
https://godbolt.org/z/W6e8YzKKf
Upvotes: 2
Reputation: 75062
sizeof(*test1)
is the size of a pointer Student*
, while sizeof(**test)
is the size of a structure Student
.The structure has a pointer, so its size should be larger than the size of a pointer.
Student **test1 = calloc(2, sizeof(*test1));
Is the typical usage. This is allocating 2-element array of Student*
and assigning the pointer to its first element to test1
.
Upvotes: 4
Reputation: 224387
Two things here:
Student *
, while in the second case you allocate space for 2 objects of type Student
. The latter is likely larger than the former, so you'll be able to put more object of type Student *
there.Upvotes: 3