Reputation: 308
I have a struct which has a pointer to array as a member and I'd like to determine the size of this array.
#include <stdio.h>
int array[]={1,2,3,4,5};
struct myStruct {
int *array;
};
struct myStruct my_struct={.array=array};
int main() {
printf("A: %d\n",sizeof(array)/sizeof(*array)); // this works
printf("B: %d\n",sizeof(my_struct.array)/sizeof(*my_struct.array)); // this doesn't work
}
This prints:
A: 5
B: 2
I expected:
A: 5
B: 5
When I use the sizeof(a)/sizeof(*a)
method on the array directly it works, but it doesn't work when used on the member of myStruct
. At first I thought that I can't assign a pointer to an array member like this, but indexing my_struct.array[i]
returns the correct values. But as I'd like to iterate over this array, I need to know its size.
Can anybody explain to me why my attempt doesn't work and how I could implement it instead?
Upvotes: 0
Views: 686
Reputation: 306
As discussed here the compiler does not know that int* array
points to an array of type int and as such sizeof() only returns the size of the pointer.
So either use std::vector
or add a size member to your struct.
Upvotes: 2