开发者

Pointer to Array of Pointers

开发者 https://www.devze.com 2023-03-08 15:15 出处:网络
I have an array of int pointers 开发者_JAVA技巧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.:

I have an array of int pointers 开发者_JAVA技巧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;


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.


Should just be:

int* array[SIZE];
int** val = array;  

There's no need to use an address-of operator on array since arrays decay into implicit pointers on the right-hand side of the assignment operator.


IIRC, arrays are implicitly convertible to pointers, so it would be:

int ** val = arr;


According to this source http://unixwiz.net/techtips/reading-cdecl.html, by using the "go right when you can, go left when you must" rule, we get the following 2 meanings of the declarations given in the previous answers -

int **val ==> val is a pointer to pointer to int
int* (*pArr)[MAX] ==> pArr is a pointer to an array of MAX length pointers to int.

I hope the above meanings make sense and if they don't, it would probably be a good idea to peruse the above mentioned source.

Now it should be clear that the second declaration is the one which moteutsch is looking for as it declares a pointer to an array of pointers.

So why does the first one also work? Remember that

int* arr[MAX]

is an array of integer pointers. So, val is a pointer to, the pointer to the first int declared inside the int pointer array.


#define SIZE 10
int *(*yy)[SIZE];//yy is a pointer to an array of SIZE number of int pointers
and so initialize yy to array as below -

int *y[SIZE];   //y is array of SIZE number of int pointers
yy = y;         // Initialize
//or yy = &y;   //Initialize


I believe the answer is simply:

int **val;
val = arr;


As far as I know there is no specific type "array of integers" in c, thus it's impossible to have a specific pointer to it. The only thing you can do is to use a pointer to the int: int*, but you should take into account a size of int and your array length.

0

精彩评论

暂无评论...
验证码 换一张
取 消