Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C pointer array

Tags:

c

pointers

When creating a pointer array in c what does the effect of adding parentheses do?

For example

int (*poi)[2];

vs

int *poi[2];

like image 595
Olychuck Avatar asked Jan 20 '12 03:01

Olychuck


People also ask

Can a pointer point to an array in C?

C. In this program, we have a pointer ptr that points to the 0th element of the array. Similarly, we can also declare a pointer that can point to whole array instead of only one element of the array. This pointer is useful when talking about multidimensional arrays.

What is the purpose of using pointer array?

Uses of pointers:To pass arguments by reference. For accessing array elements. To return multiple values. Dynamic memory allocation.

Can arrays be used as pointers?

In simple words, array names are converted to pointers. That's the reason why you can use pointers to access elements of arrays. However, you should remember that pointers and arrays are not the same. There are a few cases where array names don't decay to pointers.

What is array of pointers with example?

Following is the declaration for array of pointers − datatype *pointername [size]; For example, int *p[5]; It represents an array of pointers that can hold 5 integer element addresses.


2 Answers

Pointer to an array of 2 ints:

int (*poi)[2];

An array of two int pointers:

int *poi[2];

Normally Array has higher precedence than the pointer, but if you add the parentheses then the pointer comes "first".

like image 157
Hogan Avatar answered Sep 28 '22 04:09

Hogan


The index operator [] binds stronger than the derefentiation operator *.

int *poi[2]

translates to:

If you see poi, apply [x] to it, then dereference the result via * and you get an int. So it's an array of 2 pointers to int.

In

int (*poi)[2]

the parantheses force the * to be applied first. So anytime poi is used, if you apply * first, and then [x] you get an int. So it's a pointer to an array of 2 int.

like image 44
pezcode Avatar answered Sep 28 '22 05:09

pezcode