简体   繁体   中英

How do you access the value pointed to by a pointer inside of an array of pointers?

If I have an array of integer pointers, and I want to access the value of the integer pointed to by one of the pointers in the array, how would this be done?

Example:

 int *p0, *p1, *p2, *p3, *p4;
 int* index[5] = {p0, p1, p2, p3, p4};
 int variable1 = 1;
 int variable2 = 2;
 int variable3 = 3;
 p0[0] = variable1;
 p0[1] = variable2;
 p0[2] = variable3;

How could I access the value of 123 through the array, index[]?

If I have an array of integer pointers, and I want to access the value of the integer pointed to by one of the pointers in the array, how would this be done?

There are some possible variations, but the clearest and most conventional way would probably be to use the indexing operator, [] , to select the desired array element (a pointer) and the dereferencing operator, * , on the result to obtain the pointed-to int. The indexing operator has the higher precedence (it belongs to the single highest-precedence operator group), but if you don't remember that and are for some reason unable to look it up, then you can always use parentheses to ensure the desired order of evaluation.

Example:

int *array[2];

// ... assign valid pointer values to array elements ...

int x = *array[1];

This isn't particularly different from how you would use an array element of any other type as an operand of any other operator.

How could I access the value of 123 through the array, index[]?

The first line of your code is unnecessary and the last three lines don't do what you think they are doing.

p0[0] = variable1; //*(p0 + 0) = variable1
p0[1] = variable2; //*(p0 + 1) = variable2
p0[2] = variable3; //*(p0 + 2) = variable3

What you are telling your program to do with the first line is to go to the memory location where p0 points and store the value of variable1 there. But p0 is an uninitialized pointer so the behavior is undefined. Then you follow that up with telling your program to go to that same memory address plus an offset and to store something there. This is dangerous and will likely result in a segmentation fault.

What you want is something like this:

int* index[3];

int variable1 = 1;
int variable2 = 2;
int variable3 = 3;

index[0] = &variable1;
index[1] = &variable2;
index[2] = &variable3;

for(int i = 0; i < 3; i++){
    printf("*index[%d] = %d\n", i, *index[i]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM