Search code examples
csortingmemory-address

Different outputs of '&arrayname + n' in and outside the main function


The expression &arrayname + n is supposed to give base address + (number of elements * size of type of elements) * n and it works as expected inside the main() function.

But if I use the same in a different function, it is interpreted differently and produces different output.

Code(32-bit compiler) :

#include <stdio.h>
void arrf(int A[],int n)
{
printf("\n\nInside arrf()");
printf("\n&A ---> %p",A);
for(int i=0;i<n;i++)
    printf("\n&A + %d  ---> %p",i,(&A+i));
}

int main()
{
int A[]={1,2,3,4,5};
int n=5;
printf("Inside main()");
printf("\n&A --->%p",A);
for(int i=0;i<n;i++)
    printf("\n&A + %d  ---> %p",i,(&A+i));
arrf(A,n);
return 0;
}

Sample Ouptut:

Inside main()
&A --->0x7ffed323eac0
&A + 0  ---> 0x7ffed323eac0
&A + 1  ---> 0x7ffed323ead4
&A + 2  ---> 0x7ffed323eae8
&A + 3  ---> 0x7ffed323eafc
&A + 4  ---> 0x7ffed323eb10

Inside arrf()
&A ---> 0x7ffed323eac0
&A + 0  ---> 0x7ffed323ea88
&A + 1  ---> 0x7ffed323ea90
&A + 2  ---> 0x7ffed323ea98
&A + 3  ---> 0x7ffed323eaa0
&A + 4  ---> 0x7ffed323eaa8

Inside main(), &A+1 gives 0x7ffed323eac0 + Hex(5*4*1) = 0x7ffed323eac0 + 0x14 = 0x7ffed323ead4, as expected and so are the outputs for all &A+i

But in the arrf() function, the outputs are not as expected, even &A+0 produces an output different from the base address. More strangely, the addresses are decreasing instead of increasing. Why is that?


Solution

  • When an array is passed to a function, it is converted to a pointer to its first element. So A in main is an array while A in arrf is a pointer.

    This also means that in arrf, that &A has type int **, so pointer arithmetic is done in units of int * whose size is apparently 8 on your system.

    Also, A in arrf is a separate variable from A in main, so its address will be different (most likely on the program's stack).