5

What is the difference between these two in C. The first one is array of pointers. My main confusion is about the second declaration. What does it declare. Aren't the two the same ?

int *p []={&i,&j,&k};

int (*ar) [];
dbush
  • 205,898
  • 23
  • 218
  • 273
Neer
  • 203
  • 4
  • 13
  • Sorry.Edited that out. Thank you. – Neer Jul 17 '17 at 12:24
  • 2
    ["declare p as array of pointer to int"](https://cdecl.org/?q=int+*p+%5B%5D), ["declare ar as pointer to array of int"](https://cdecl.org/?q=int+%28*ar%29+%5B%5D) – Kijewski Jul 17 '17 at 12:24
  • Take a look at [this answer](https://stackoverflow.com/a/30345939/4265352) on a similar question. – axiac Jul 17 '17 at 12:24
  • 1
    Array of pointers versus a pointer to an array. Two very different things. The second (pointer to array) will not compile since the array need a size. – Some programmer dude Jul 17 '17 at 12:25
  • `p` is an array of pointers to ints, initialized with three values (and so the array size is 3). `ar` is a pointer to an array of integers. – Paul Ogilvie Jul 17 '17 at 12:25
  • `int (*ar) [];` => `ar` is a pointer to an array of int. – msc Jul 17 '17 at 12:35

2 Answers2

6

Just follow the "right-left" rule

int *p []={&i,&j,&k}; // reads: "p is an array of pointers to int"

int (*ar) []; // "ar is a pointer to an array of ints"

K. Kirsz
  • 1,384
  • 10
  • 11
4

The two are not the same. The second is a pointer to an array of int.

You can use such a declaration as a function parameter when passing a 2D array as a parameter. For example, given this function:

void f(int (*ar)[5])    // array size required here to do pointer arithmetic for 2D array
{
    ...
}

You could call it like this:

int a[5][5];
f(a);

Another example as a local parameter:

int a[5] = { 1,2,3,4,5 };
int (*ar)[];   // array size not required here since we point to a 1D array
int i;

ar = &a;
for (i=0;i<5;i++) {
    printf("a[%d]=%d\n", i, (*ar)[i]);
}

Output:

a[0]=1
a[1]=2
a[2]=3
a[3]=4
a[4]=5
dbush
  • 205,898
  • 23
  • 218
  • 273
  • Thank you so much, can they be declared and used inside a function( not in the parameter) ? If not then why is there a scope to declare such things inside a function. – Neer Jul 17 '17 at 12:29
  • @Neer Yes they can. See my edit for an example. – dbush Jul 17 '17 at 12:32