-5

Normally to find the size of the array, we do..

int A[]={1,2,67,9,0,-1,-90};
int n=sizeof(A)/sizeof(A[0]);
printf("the size of the array is %d\n", n);`

The output of the above code shows size as 7. But when A is put into some pointer and then, if we try to do the same, it shows

int A[]={1,2,67,9,0,-1,-90};
int *B=A;
int n=sizeof(B)/sizeof(B[0]);
printf("the size of the array is %d\n", n);

the answer is 2

How do I find the size of the array using this pointer.

  • I'm assuming you're on a 64bit O/S and machine.... If so, the pointer is (probably) 8 bytes, the int is 4 bytes. 8/4 == 2. If you looked at the size of the thing that the pointer is pointing to you may have more luck! – Joe Feb 09 '16 at 11:34
  • 1
    See also [Is an array name a pointer in C?](http://stackoverflow.com/q/1641957/1015722) – Jeremy Rodi Feb 09 '16 at 11:44
  • It comes into mind there might be a reason a **pointer** is not called "array". Maybe because **a pointer is not an array**? – too honest for this site Feb 09 '16 at 12:52
  • > How do I find the size of the array using this pointer. No - not possible. – artm Feb 10 '16 at 11:46

1 Answers1

5

int n=sizeof(B)/sizeof(B[0]);

The result is 2 because sizeof(B) is sizeof( pointer ) NOT sizeof( array )

int A[]={1,2,67,9,0,-1,-90};
int *B=A;    // <-- B is a pointer pointing to the first element of array A
int n=sizeof(B)/sizeof(B[0]);    // <-- sizeof(pointer) / sizeof(int)

The result is machine-dependent, but you can verify that the output of these two printfs are the same:

printf( "sizeof(B)/sizeof(B[0]) = %zu\n", sizeof(B)/sizeof(B[0]) );
printf( "sizeof(int *)/sizeof(int) = %zu\n", sizeof(int *)/sizeof(int));
artm
  • 17,291
  • 6
  • 38
  • 54