-3

I declare an array that can hold 10 parameters:

int a[10] = {2,3};

But I actually have 2 parameters, when I use sizeof() :

int n = sizeof(a) / sizeof(int); 

It showed the length of the array is 10, but I want the result is: 2 as I only got 2 parameters. How can I do that ? Thx.

  • 2
    Amount of items in array is fixed at 10, amount of initializers does not matter. The rest of items are initialized with zeroes. – user7860670 May 15 '21 at 09:06
  • 1
    That's because arrays have a fixed size, set at compile time to the number of elements you specified. That *is* its size. It doesn't matter how many elements you initialize, the size will never change. If you want a dynamic "array" use `std::vector` instead. – Some programmer dude May 15 '21 at 09:07

1 Answers1

4

The actual length of the array is 10, not 2. When you provide fewer elements than the array holds, the rest will be filled with zeros.

If you’d like to size the array based on how many values it’s initialized with, just leave the size out of the declaration: int a[] = {2,3};.

Sneftel
  • 40,271
  • 12
  • 71
  • 104