Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer to Array of Pointers

Tags:

arrays

c

pointers

I have an array of int pointers int* arr[MAX]; and I want to store its address in another variable. How do I define a pointer to an array of pointers? i.e.:

int* arr[MAX];
int (what here?) val = &arr;
like image 874
moteutsch Avatar asked May 25 '11 20:05

moteutsch


People also ask

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

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 do you declare an array of 10 pointers pointing to integers?

int (*ptr)[10]; Here ptr is pointer that can point to an array of 10 integers. Since subscript have 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 10 integers'.

How do you create an array of pointers in C++?

Consider this example: int *ptr; int arr[5]; // store the address of the first // element of arr in ptr ptr = arr; Here, ptr is a pointer variable while arr is an int array. The code ptr = arr; stores the address of the first element of the array in variable ptr .

What is difference between pointer to array and array of pointers?

A user creates a pointer for storing the address of any given array. A user creates an array of pointers that basically acts as an array of multiple pointer variables. It is alternatively known as an array pointer. These are alternatively known as pointer arrays.


1 Answers

The correct answer is:

int* arr[MAX];
int* (*pArr)[MAX] = &arr;

Or just:

        int* arr  [MAX];
typedef int* arr_t[MAX];

arr_t* pArr = &arr;

The last part reads as "pArr is a pointer to array of MAX elements of type pointer to int".

In C the size of array is stored in the type, not in the value. If you want this pointer to correctly handle pointer arithmetic on the arrays (in case you'd want to make a 2-D array out of those and use this pointer to iterate over it), you - often unfortunately - need to have the array size embedded in the pointer type.

Luckily, since C99 and VLAs (maybe even earlier than C99?) MAX can be specified in run-time, not compile time.

like image 134
Kos Avatar answered Nov 15 '22 21:11

Kos