Take this example:#include int main (){ int a [5]; a [3] = 1111; printf ("3[a] = %dn", 3[a]); return 0;}You notice that I use 3[a] instead of a[3], however, this code works fine but I don't know how.It will be grateful if someone explians to me why and how this code works fine.Thanks.

Showing Answers 1 - 15 of 15 Answers

Suneet Jain

  • Nov 20th, 2006
 

you have taken 3[a] as a string. Thats why iot is working. Remove string quotes and try, it won't work.

  Was this answer useful?  Yes

Vamshi

  • Nov 22nd, 2006
 

int a[5]; // This line is creating a unintialized array of 5 integers. a [3] = 1111; // Here Ur intializing the 4th element to 1111printf ("3[a] = %dn", 3[a]); // By saing 3[a] compiler takes it as a[3] and as it is intialized to 1111 u will see 1111 printed on screen.In 3[a].... 3 is displacement/index in the array : a. try out this to understand: int a[5] = {1,1,1,1,1};a[3] = 1111;ptintf("1[a] = %d t 3[a] = %d",1[a],3[a]);Note : diplacement/index starts from 0.

  Was this answer useful?  Yes

Bhushan

  • Jan 21st, 2007
 

regarding that printf statement.......... a[3] is internally calculated by compiler as (a+3). so 3[a] will be calculated

as (3+a) . and these two statements calculates the same value and this is the reason why that code works.  (Name of array itself acts as starting address of the array.)

mytest1

  • Jan 30th, 2007
 

whenever u declare a array, the name of the array( i.e the array variable) is actually a pointer to the starting address of the memory area that was reserved for the array..for ex:int arr[10];here "arr" is actually a pointer pointing to the starting position of the contiguous memory that was allocated for the arrayi. if the following memory was allocated for the array000 001 002 003 004 005 006 007 008 009then, arr is pointing to 000when u use the [] to access an array, the value within the array is added to the value of the base pointer(arr)i.e arr[3] = *(arr+3) = *(000+3) + *(003)so arr[3] = 3[arr] = *(arr+3) = *(3+arr)hope that solves ur doubt

winny gupta

  • Feb 15th, 2007
 

the above code works fine. This is so because when the program runs, an array is internally converted to a pointer notation,i.e., *(a + 3) for a[3]. The same notation,i.e. *(a+3) is achieved for 3[a]. Hence, the above code works perfectly well. This is valid only in printf statement and not in the scanf statement.

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions