1

Consider the below code snippet:

int x[] ={10,20,30,40,50};
int *p;
int **q;

p = x;    /* Obviously p now holds base address of array. So no problem here */ 
q = &x;   /* Error. Why? */

I am getting this error in gcc compiler.

error: cannot convert ‘int (*)[5]’ to ‘int**’ in assignment q = &x; 

An array variable can be considered as constant pointer to first element of the array. Then why cant I assign the address of the constant pointer i.e) &x to pointer of pointer variable q ?

6
  • 1
    Because &x is of type int (*)[5], not int ** — just like the error message says. They're quite different types, as you can see from the spelling. Trying to treat the value as an array of pointers would lead to horrible problems because it isn't an array of pointers. Commented Dec 22, 2016 at 2:28
  • @JonathanLeffler but the compiler has allowed the assignment from int [] to int *, so what's the difference? Commented Dec 22, 2016 at 2:29
  • 1
    I'll say it again and again: Arrays are not pointers and pointers are not arrays. cc @lxop Commented Dec 22, 2016 at 2:30
  • The & is the difference. What else do you think could be the cause of the trouble? Commented Dec 22, 2016 at 2:30
  • @JonathanLeffler So how can I assign &x Commented Dec 22, 2016 at 2:31

1 Answer 1

3

An array decays to a pointer in certain contexts, like assignment, or passing it to a function.

The address-of operator, &, does not decay the array into a pointer. It's as simple as that. Instead, you get a pointer to the array. In this case:

int (*q)[5];

q= &x;  // Works just fine
Sign up to request clarification or add additional context in comments.

1 Comment

Is it worth noting that you can then use q[0][3] = 41; or (*q)[2] = 31; to increment the values 40 and 30 in the array (or, more accurately, to reassign the values so that they are one larger than the previous values, but there isn't a formal increment in sight, though q[0][1]++ would work fine and is an increment, of course.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.