0

I've got array on the top of the code

int numberArray[] = {1, 2, 3, 4, 5};

And I would want to bring pointer from this array to another pointer in function

    void movePointer(int* anotherPointer)
    {
        anotherPointer = numberArray;
    }

And now I would use anotherPointer in the rest of code. How I should to do this? I thougth about pointer from pointer, but I received nothing interesting.

4
  • 2
    You should read about pointers and functions in a good C book. That is a very basic question and is treated in every book about programming in C in detail. While the question might have a simple answer, it will not help you mucht. There seems to be an XY-problem, where you want to accompish something, but ask the wrong question actually. This is apparently due to lacking knowledge of yours - no offense!! Commented Jun 16, 2015 at 12:39
  • Note that you cannot define a function in another function. While some compiler (like gcc) do allow this as an extension, it is non-standard and should not be used. Commented Jun 16, 2015 at 12:40
  • Yes, I know! But maybe I can't see something in way I was trying already. Commented Jun 16, 2015 at 12:41
  • True that, I'm tried edit it to look better and I done this big mistake. Commented Jun 16, 2015 at 12:42

2 Answers 2

2
void movePointer(int ** anotherPointer)
{
    *anotherPointer = numberArray;
    int a = (*anotherPointer)[1]; // value 2
}
Sign up to request clarification or add additional context in comments.

2 Comments

But I would want to use anotherPointer outside of movePointer function.
Demo usage: int * my_ptr; movePointer( &my_ptr ); int a = my_ptr[0];.
0

Remember, that anotherPointer is local variable - available only in body of this function. When you are passing variable as a pointer to the function, there is created a copy of this pointer inside this function. In this code:

void movePointer(int* anotherPointer)
{
    anotherPointer = numberArray;
}

you are trying do modify the address stored in anotherPointer. And you will, but only in the scope of this function. Outside that function the adress was not modified. The best solution is passing "pointer to pointer" as an argument like @i486 showed in his answer.

Comments

Your Answer

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