LOOK THE FOLLOWING CODE:

 void main()
 {
      char a[]={'a','b','c',d'};
      int b[]={1,2,3,4,5};
       printf("%d   %d",&a[3]-a,&b[3]-b};
 }

OUTPUT:

       3   3

CAN SOMEBODY EXPLAIN ME WHY THE OUTPUT IS SAME.
ACCORDING TO ME OUTPUT IS (3 6).

Edited 3 Years Ago by pyTony: fixed formating

Okay... umm because you just did 4-1 and 4-1...

array[3] refferences the fourth element (i.e. the number four in your case).
array (by itself) refferences the beginning element i.e. array[0].

array = 1
array[3] = 4

4 - 1 = 3

If you wanted the second argument to output a number 6, you would have to declare array b to hold numbers up to 7, and then subtract b[0]. Or you could do printf("%d %d", &a[3]-a, &b[3]+b) that would produce 3 6 also.

char a[]={'a','b','c',d'};
int b[]={1,2,3,4,5};
printf("%d %d",&a[3]-a,&b[3]-b};

You are taking the difference between pointers; the result is the number of objects between the two addresses. There are three objects between element 0 and element 3, regardless of the size of the objects.

I tried to edit this into my previous reply, but I guess you can only edit within 30 minutes of posting.

#include <stdio.h>
 
int main()
{
   char a[] = { 'a', 'b', 'c', 'd' };
   int  b[] = { 1, 2, 3, 4, 5 };
 
   printf("a = %p <-> &a[0] = %p; *a = '%c' <-> a[0] = '%c'\n",
		  (void*)a, (void*)&a[0], *a, a[0]);
   printf("sizeof(*a) = %d\n", (int)sizeof(*a));
   printf("&a[0] = %p, a[0] = '%c'\n", (void*)&a[0], a[0]);
   printf("&a[3] = %p, a[3] = '%c'\n", (void*)&a[3], a[3]);
   printf("&a[3] - &a[0] = %d\n", (int)(&a[3] - &a[0]));
 
   putchar('\n');
 
   printf("b = %p <-> &b[0] = %p; *b = %d <-> b[0] = %d\n",
		  (void*)b, (void*)&b[0], *b, b[0]);
   printf("sizeof(*b) = %d\n", (int)sizeof(*b));
   printf("&b[0] = %p, b[0] = %d\n", (void*)&b[0], b[0]);
   printf("&b[3] = %p, b[3] = %d\n", (void*)&b[3], b[3]);
   printf("&b[3] - &b[0] = %d\n", (int)(&b[3] - &b[0]));
   return 0;
}
 
/* my output
a = 0012FF88 <-> &a[0] = 0012FF88; *a = 'a' <-> a[0] = 'a'
sizeof(*a) = 1
&a[0] = 0012FF88, a[0] = 'a'
&a[3] = 0012FF8B, a[3] = 'd'
&a[3] - &a[0] = 3
 
b = 0012FF74 <-> &b[0] = 0012FF74; *b = 1 <-> b[0] = 1
sizeof(*b) = 4
&b[0] = 0012FF74, b[0] = 1
&b[3] = 0012FF80, b[3] = 4
&b[3] - &b[0] = 3
*/

look &b[3] = b + 3 (using pointer arithemetic)

therefore &b[3] - b = b + 3 - b = 3.

hence ur ans.

regards.

This article has been dead for over six months. Start a new discussion instead.