scope of a pointer?

This is a discussion on scope of a pointer? within the C++ Programming forums, part of the General Programming Boards category; If a pointer is passed to a function, does it go out of scope when the function returns? Maybe a ...

scope of a pointer?

If a pointer is passed to a function, does it go out of scope when the function returns? Maybe a better way to ask would be, I send a pointer of array x to a function. The function does some stuff then increments the pointer. I know that since it's a pointer, any data that the pointer points to will stay changed, but will the pointer stay incremented (pointing to the next location in the array) after said function has ended? If not, then would 2 possible solutions to have it stay incremented be either looking up how to send a pointer pass-by-reference or use the pointer as the return value? Right now i'm sending an int by reference and using it to index the array, but it seems ugly and excessive since i'm sending a pointer already.

No, the pointer will not stay incremented (just like the int wouldn't stay incremented if you passed it to by value). You can pass a pointer by reference: (int*& p). I don't think you can pass an array pointer by reference, but you shouldn't have to since the pointer syntax works as well.

Essentially, if the workings of a function change any argument that is passed by value to the function, then that change is not visible to the caller. If you want the change to be visible then, yes, you must pass either a pointer or a reference to the thing you want changed. If you want the change to a pointer to be visible, you must either pass a pointer to pointer or a reference to pointer. However, you cannot do that with an array;

If a pointer is passed to a function, does it go out of scope when the function returns?

Anything that is passed to a function is copied and then assigned to the function parameter variable. Therefore anything you do to the function parameter variable has no effect on the original variable. When the function ends, the function parameter variable is destroyed.

Inside a function, you can change the thing that is located at the address stored in a pointer. A pointer is an address and when it is copied for a function, the copy of the address still refers to the same location in memory, and you can use the copy of the address to access the original thing that is stored there. However, if you try to assign a different address to a function parameter variable that is a pointer, either by using pointer arithmetic or by using outright assignment, the address stored in the original pointer variable will remain unchanged.