izzzi izzzi - 5 months ago 35
C Question

C not allocating memory for array of structs correctly?

struct student{
int id;
int score;

struct student* allocate(){
struct student* students = (struct student*)malloc(sizeof(struct student)*10);
return students;

void generate(struct student* students){
int i=0;
printf("%lu\n", sizeof(students));
printf("%lu\n", sizeof(struct student));
int length = sizeof(students)/sizeof(struct student);
printf("%d\n", length);

I have this code which should create an array of 10 student structs. When I get to the generate function and try to see how much memory the students array had allocated it only says 8 bytes, the same as a single student struct itself and when I get to the for loop it is only printing "hi" once when it should be 8 times. What have I done wrong?




What have I done wrong?

students is a pointer, so sizeof(students) gives you the size of a pointer. It does not give you the size of the array that students points to.

Frustratingly enough, sizeof(*students) also doesn't work - it gives you the size of one student, not the size of the whole array. That's because students only points to the first student, as far as the compiler is concerned.

There is no built-in way to get the size of an array, given a pointer to the start of it. You need to keep track of the size yourself.