EnterKEY - 10 days ago 5

C Question

`int (*a)[5];`

How can we Initialize a pointer to an array of 5 integers shown above.

Is the below expression correct ?

`int (*a)[3]={11,2,3,5,6};`

Answer

Suppose you have an array of int of length `5`

e.g.

```
int x[5];
```

Then you can do `a = &x;`

```
int x[5] = {1};
int (*a)[5] = &x;
```

To access elements of array you: `(*a)[i]`

(== `(*(&x))[i]`

== `(*&x)[i]`

== `x[i]`

) parenthesis needed because precedence of `[]`

operator is higher then `*`

. (one common mistake can be doing `*a[i]`

to access elements of array).

Understand what you asked in question is an compilation time error:

```
int (*a)[3] = {11, 2, 3, 5, 6};
```

It is not correct and a type mismatch too, because `{11,2,3,5,6}`

can be assigned to `int a[5];`

and you are assigning to `int (*a)[3]`

.

Additionally,

You can do something like for one dimensional:

```
int *why = (int[2]) {1,2};
```

Similarly, for two dimensional try this(thanks @caf):

```
int (*a)[5] = (int [][5]){ { 1, 2, 3, 4, 5 } , { 6, 7, 8, 9, 10 } };
```