19aksh
19aksh

Reputation: 123

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?

Upvotes: 2

Views: 81

Answers (2)

Sreeraj Chundayil
Sreeraj Chundayil

Reputation: 5859

When you are passing address of a array into a function it has no information(of the number of array elements) that how was the previous pointer incrementation used to work. To overcome that you may need to explicitly tell the compiler that how should the arithmetic of the pointer behave.

I have modified the example for you to make it work.

#include <stdio.h>
void arrf(int (*A)[5],int n)//Here
{
  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);//Here
        return 0;
}

Also read about : c-pointer-to-array-array-of-pointers-disambiguation

Upvotes: 1

dbush
dbush

Reputation: 223872

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).

Upvotes: 3

Related Questions