Anjan Anjan - 2 months ago 17
C Question

sizeof array elements in C

In

C
, array elements are treated as pointers. So the expression
sizeof(arr)/sizeof(arr[0])
becomes
sizeof(int *)/sizeof(int)
which results in
1
then why the following program give output is
12 11
.

#include <stdio.h>

int main()
{
int n1, n2;
char arr1[] = "Hello World";
char arr2[] = {'H','e','l','l','o',' ','W','o','r','l','d'};
n1 = sizeof(arr1)/sizeof(arr1[0]);
n2 = sizeof(arr2)/sizeof(arr2[0]);
printf("n1 = %d\nn2 = %d\n", n1, n2);
return 0;
}

Answer

array elements are treated as pointers

It is not a true. Arrays are NOT pointers. But they decay to pointers to first element when are passed to functions. And sizeof(array) is the number of bytes that whole array occupies.

Comments