0

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?

Sim Son
  • 310
  • 1
  • 10
  • 1
    First array that you declare globally is **statically** allocated , thus when you call `sizeof(array)` it gives you the number of bytes it uses totally . The array inside your struct though isn't really an array , it's just a pointer , so `sizeof(struct.array)` just gives you the size of the pointer which seems to be 4 in your computer and thus 4 / 2 = 2 . Change `int *array` to `int array[5]` from inside your struct and you will see the desired results. – fvalasiad May 20 '21 at 12:05
  • @fvalasiad hmm, I see. I actually would like to have this array to be of variable size. Is there a way around it or is it generally not possible in C++? – Sim Son May 20 '21 at 12:12
  • Do you wish to use a dynamic array? If that's the case use `std::vector`. Unless you mean that you want to create a dynamic array yourself, if that's the case you should add a `size_t size` property inside your struct to hold the array's size and dynamically reallocate memory accordingly. – fvalasiad May 20 '21 at 12:14
  • @fvalasiad the array won't change during runtime, but I want to have several instances of this struct, each with arrays of different size. But including the `size` property will work for me. Thanks for your help! – Sim Son May 20 '21 at 12:18

1 Answers1

2

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.

Klickmann
  • 130
  • 8
  • 2
    `int* array` is never an array. It’s a pointer. It points at an `int`. That `int` might be the first element in an array of `int`, but, as this answer suggests, it is still just a pointer. +1. – Pete Becker May 20 '21 at 17:53