Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

address of pointer to C multi-dimension array

Question from code below:

#include <stdio.h>

int main(int argc,char *arg[]){

    if (argc>2){
      int m=atoi(arg[1]);
      int n=atoi(arg[2]);

      int a[m][n];
      int (*p)[m][n]=&a;

      printf("p : %p, *p : %p, **p : %p\n",p,*p,**p);
    }

    return 0;
}

Main Env: gcc version 4.6.3 (Ubuntu/Linaro 4.6.3-1ubuntu5) x86-64

gcc main.c
./a.out 2 4

output:

p : 0xbfea7ef0, *p : 0xbfea7ef0, **p : 0xbfea7ef0

Question is why p == *p == **p. I think this may be because a is an array, kind of constant pointer which address is something specific, and this involves some implementation detail of gcc.

like image 869
Mamrot Avatar asked Oct 11 '25 22:10

Mamrot


1 Answers

p is a pointer to an array with dimensions [m][n]. The value of that pointer is the address of a, so printing p gets you the address of a.

*p is an array with dimensions [m][n]. The "value" of this as a pointer is a pointer to the first element of the array, which is a[0]. This is the same address as a.

**p is an array with dimensions [n]. The value of this pointer is a pointer to the first element of the array, which is a[0][0]. This is the same address as a again.

like image 179
nneonneo Avatar answered Oct 14 '25 11:10

nneonneo