Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C pointer to array/array of pointers disambiguation

What is the difference between the following declarations:

int* arr1[8]; int (*arr2)[8]; int *(arr3[8]); 

What is the general rule for understanding more complex declarations?

like image 672
George Avatar asked May 13 '09 18:05

George


People also ask

How do you declare a pointer to an array of pointers to?

To declare a pointer to an array type, you must use parentheses, as the following example illustrates: int (* arrPtr)[10] = NULL; // A pointer to an array of // ten elements with type int. Without the parentheses, the declaration int * arrPtr[10]; would define arrPtr as an array of 10 pointers to int.

How array can be traversed with the pointers?

This is done as follows. int *ptr = &arr[0]; After this, a for loop is used to dereference the pointer and print all the elements in the array. The pointer is incremented in each iteration of the loop i.e at each loop iteration, the pointer points to the next element of the array.

Is there any relation between pointers and array name?

The only difference between an array name and a normal pointer variable is that an array name always points to a specific address, which is the starting address of the array. Pointers are flexible and can point to wherever you want them to point.

How do you declare a pointer to an array of pointers to int int * A 5?

int (*ptr)[5]; Here ptr is a pointer that can point to an array of 5 integers. Since subscript has higher precedence than indirection, it is necessary to enclose the indirection operator and pointer name inside parentheses. Here the type of ptr is 'pointer to an array of 5 integers'.


1 Answers

int* arr[8]; // An array of int pointers. int (*arr)[8]; // A pointer to an array of integers 

The third one is same as the first.

The general rule is operator precedence. It can get even much more complex as function pointers come into the picture.

like image 141
mmx Avatar answered Oct 15 '22 14:10

mmx