Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
412 views
in Technique[技术] by (71.8m points)

c - Pointer to Array of 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;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...