Sim Son
Sim Son

Reputation: 308

(C++) Array as member of struct: how to get its size?

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

Answers (1)

Klickmann
Klickmann

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

Related Questions