0

I have been wondering why the following snipped of code:

int x[10];
int **x_p = &x;

causes an Assignment/initialization from incompatible pointer type warning, and therefore runtime errors.

If this it not the correct syntax, how do I declare a pointer to int[n], where n is known at runtime?

If this sounds like bad practice, why? Should I use int *x = malloc(10 * sizeof(int)) instead?

I will appreciate any learnings I can achieve from this. I have gone through a bunch threads with the same title but couldn't find a satisfying answer.

Jytug
  • 1,072
  • 2
  • 11
  • 29

1 Answers1

2

Pointer to an array of 10 int elements - int (*ptr)[10] which is certainly not int**. hence type mismatch. When x is used as an operand to & the x doesn't decay into pointer (int*). The address of the array object is int(*)[10] not int**.

It is a practice with application of its own. int *x = malloc(..) is quite different from int x[10] with respect to lifetime, storage duration and its usage that changes based on that.

Arrays are not pointers - on most situations it is converted into one (array decaying) - but that doesn't make it a pointer. For example when array is used as operand of &,sizeof operator it doesn't decay into pointer.

The standard C11 N1570 says about this array decaying, as it is a core idea used in this question itself and it's answer will mention it. From §6.3.2.1¶3

Except when it is the operand of the sizeof operator, the _Alignof operator, or the unary & operator, or is a string literal used to initialize an array, an expression that has type 'array of type' is converted to an expression with type 'pointer to type' that points to the initial element of the array object and is not an lvalue. If the array object has register storage class, the behavior is undefined.

user2736738
  • 30,591
  • 5
  • 42
  • 56
  • Thanks, I was confused there for a while, being taught since boyhood that arrays are basically pointers in C. I think for non-compile-time sizes I can declare a pointer as `int (*x_p)[]` – Jytug Feb 08 '18 at 20:34