1

I have variable

int v1, v2; 

I have two pointers:

int *ptr1, *ptr2;

and an array of pointers

int *array[2] = {ptr1, ptr2};

It is possible to change the ptr1 using pointer array to do operation like ptr1 = &v2

array[0] = &v1; (I know this record is wrong, but I mean the idea of writing new value into the ptr1 pointer)

2
  • 3
    No, it's not possible because array stores copy of pointer. To do so store pointer to pointer. int * ptr1 = &v1; int **arr[] = {&ptr1}; *arr[0] = &v2; Commented May 18, 2017 at 7:50
  • @user7408320 Which language? C? C++? Commented May 18, 2017 at 8:01

1 Answer 1

3

You can't do it with a int* [] (array of pointer), because the element of array is just a copy, then any modification on the element has nothing to do with the original pointer. So array[0] = &v1; won't change ptr1.

You can use a int** [] (array of pointer to pointer) instead, e.g.

int **array[2] = {&ptr1, &ptr2};

then

*array[0] = &v1;  // this will make ptr1 point to v1
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.