Dark Innocence Dark Innocence - 1 month ago 5x
C Question

How come does the size of arr[0] is of 8 bytes?

I was browsing for finding a way to find number of rows and columns in of a given matrix without any additional information and I came around this answer.

Given a matrix, find number of rows and columns

This is the code snippet from the second answer of the question above :

int main()
float a[9][2]={{0,1},{1,1}};
int row=(sizeof(a)/sizeof(a[0]));
int col=(sizeof(a)/sizeof(a[0][0]))/row;
return 0;

How does the sizeof(a[0]) turns out to be 8? In my understanding the pointers have a generic size of 4 bytes in 32 bit arch and 8 bytes in 64 bit arch. I printed out the sizeof(a[0]) on both the machines and the answer is still 8.
Anybody has any clue why?

Edited : I mean to say doesn't a[0] decay into a pointer?


There are no pointers used anywhere in the code posted. Arrays do not decay to a pointer-to-first-element when passed as operand to sizeof (1).

  • a is a 2D array, of type float [9][2].
  • a[0] is the first item in this 2D array, which is a 1D array of type float [2].
  • sizeof(a) gives the size of the 2D array, equivalent to sizeof(float) * 9 * 2.
  • sizeof(a[0]) gives the size of the 1D array, equivalent to sizeof(float) * 2.
  • float is apparently 4 bytes on your system, 4 * 2 = 8.

(1) See the specification of the sizeof operator in ISO 9899:2011

When applied to an operand that has array type, the result is the total number of bytes in the array.

The rule of "array decay" is found in

Except when it is the operand of the sizeof operator, or the unary & operator, or is a string literal used to initialize an array, an expression that has type ‘‘array of type’’ is converted to an expression with type ‘‘pointer to type’’ that points to the initial element of the array object and is not an lvalue.