-1

In C++, how do I check the allocated value/size a struct array has been initialized to?

int main()
{
    struct A
    {
      int x;
      int y;
    };
    A* a = new A[20];
}
sizeof(a) / sizeof(a[0]);

returns a value of 1. So this is not what I was expecting.

Is there any way I can do this so that I can get the size (20) allocated for a?

Where I am going to use it is in a case like this:

void fillArray(A valueToFill, int matrixSize, A *a)
{
    for (int i = 0; i < matrixSize; i++)
    {
        a[i] = valueToFill;
    }
}

I intend to check if size of a is actually matrixSize. Otherwise it will crash if matrixSize is bigger than a.

kzaiwo
  • 1,558
  • 1
  • 16
  • 45

1 Answers1

1

Introduce a new variable (I used na below)

int main()
{
    struct A
    {
      int x;
      int y;
    };
    size_t na = 20;
    A* a = new A[na]; // invalid C
}

then, when you need the size, just refer to (the possibly updated) na

printf("current number of elements: %d\n", (int)na);
pmg
  • 106,608
  • 13
  • 126
  • 198