2

Consider the following C code snippet:

int main() {
  int *crr;
  int arr[] = {1, 2, 3, 45};
  crr = (int *)malloc(sizeof arr);
  printf("%ld\n", sizeof arr);
  printf("%ld", sizeof crr);
  return 0;
}

The output of the above code is :

16
8

I have 64 bit architecture system. Hence, int is 4 bytes. Need explanation or any references for why this is happening. I've allocated same amount of memory to the crr.

Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
taurus05
  • 2,491
  • 15
  • 28

1 Answers1

3

sizeof arr evaluates to the size of arr in bytes. Because arr is an array of four four-byte int, its size is 16 bytes.

sizeof crr evaluates to the size of crr. Because crr is an eight-byte pointer, its size is eight bytes.

You may be accustomed to the fact that arrays are often automatically converted to pointers. When an array is passed to a function, it is converted to a pointer. When an array is used in an index expression, such as arr[2], it is converted to a pointer (and then the index is added to it with pointer arithmetic, and the resulting pointer is dereferenced, as if it had been written *(arr+2)). This automatic conversion does not occur with sizeof. C 2018 6.3.2.1 3 says:

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…

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312