Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sizeof-operator reverse behavior

Tags:

c

sizeof

we know that when we use array it hold address of first element and &array is store whole array address its true when i use in printf but in sizeof operator it is reverse behavior why

i am using code-block with GCC on windows 7

 int main(void)
  {
    int c[5];
      printf(" %d  %d  %d  %d\n",c,c+1,&c,&c+1);\\when we add 1 in "c" it add more 4 bytes and when "&c+1" it add 20 byte witch is true

       printf(" %u  %u ",sizeof(c),sizeof(&c));\\But when we print first element size (with "c") it give 20 byte and when print (With "&c") whole arry size it give 4 byte


         return 0;
            }

\i cant understand why please explain

like image 293
Manpreet Sidhu Avatar asked Dec 23 '22 22:12

Manpreet Sidhu


1 Answers

I think what you need to know here is, &array is still a pointer, just the type differs.

For an array like int arr[]={4,3,2,1,0}

  • Most cases, arr is same as &arr[0], i.e., int *, but with sizeof operator, it behaves differently (see note below). When passed to sizeof operator, it gives you the size of the whole array, i.e., sizeof(int [4]) in this case.
  • &arr is of type int (*)[4], and it's a pointer.

So, to get the number of elements in the array, you should do something like

printf ("Number of elements = %zu", sizeof(arr)/sizeof(arr[0]));
            / *(size of the entire array / size of one element in the array) */

Quoting C11, chapter §6.3.2.1 (emphasis mine)

Except when it is the operand of the sizeof operator, the _Alignof 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. [...]

That said,

  • sizeof yields a result of type size_t, you should use %zu format specifier to print the result.
  • to print a pointer to an object, you must use %p format specifier and cast the corresponding argument to void *.
like image 189
Sourav Ghosh Avatar answered Jan 04 '23 00:01

Sourav Ghosh