-5

I created an array like this: int thisArray[20] = {0,1,2,3,4,5,6,7,8,9};

Then I created a variable to store the size of the array:

int this = sizeof(thisArray);

When I tell the program to print the value of this it shows me 80 instead of 20.

What am I doing wrong?

Maityar
  • 5
  • 1

2 Answers2

4

When you give an initializer without explicitly initializing everything, anything not explicitly set will be set to 0.

Section 6.7.9 p 21 of the C11 standard:

If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.

And the rules for static storage duration referenced here are in 6.7.9 p 10

If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. If an object that has static or thread storage duration is not initialized explicitly, then:

  • if it has pointer type, it is initialized to a null pointer; — if it has arithmetic type, it is initialized to (positive or unsigned) zero;
  • if it is an aggregate, every member is initialized (recursively) according to these rules, and any padding is initialized to zero bits;
  • if it is a union, the first named member is initialized (recursively) according to these rules, and any padding is initialized to zero bits;

As for why you get 80 instead of 20 for sizeof because an int is presumably 4 bytes on your system, so 20 * 4 = 80 bytes.

Christian Gibbons
  • 4,272
  • 1
  • 16
  • 29
1

You're not doing anything wrong, you just have to reset your expectations.

sizeof evaluates to the size of the array in bytes, not the number of elements. You declared thisArray to have 20 elements of type int, and it's a good bet sizeof (int) on your system is 4. Thus, the result of sizeof on this object will be 80.

There's a trick to get the number of elements in an array:

size_t elements = sizeof myArray / sizeof myArray[0];

That is, you take the total size of the array (80 bytes) and divide by the size of a single element (4 in this case). Note that this trick will only work if the operand of the first sizeof is an array type (that is, declared as T arr[N]). If it's a pointer type, then this won't work - you'll be dividing the size of the pointer object by the size of an array element.

John Bode
  • 119,563
  • 19
  • 122
  • 198