Reputation: 8717
This is a follow on question to an earlier one.
I have learned some errors of my ways, but have extra questions. My objective is to have a local array in one method changed from another method without the use of any global variables.
void methodOne(){
int myArray[10] = {0};
int *pMyArray = myArray;
methodTwo(&*pMyArray);
}
This should be declaring an array of null values and passing a reference to the second array as I was shown how to do so correctly here.
void methodTwo(int *passedPointer){
int *localPointer = passedPointer;
}
Next I'd like to change the values of myArray from methodTwo. So to change the first [0]
element I would say:
*localPointer = 1;
Is this correct?
Then to change the next element would I increment the pointer using:
localPoint++;
*localPointer = 2;
Would this change the second value in myArray? I'm not sure thats the correct way to do it is it?
TIA
Upvotes: 0
Views: 10111
Reputation: 146930
No, this is wrong. Very wrong. Array to pointer decay is really, really bad and you should never, ever, use it. Use a class-based wrapper like std::array
, and pass in a pair of iterators to MethodTwo.
Upvotes: 0
Reputation: 26341
First, you pass the array incorrectly. An array is nothing more than a pointer to the first, element, so you don't need to take it's address to pass it to MethodTwo
. However, what you should do, is pass in the number of elements in that array to MehtodTwo
:
methodTwo(MyArray, 10);
Since an array is nothing other than a pointer to the first element, you can directly index into the array without requiring the use of pointer arithmetics:
void methodTwo(int passedArray[], size_t n)
// alternative void methodTwo(int *passedArray, size_t n)
{
passedArray[0] = passedPointer;
}
Upvotes: 0
Reputation: 490148
Yes, this all looks like it should work. Generally when you're passing an array to a function, you don't assign to a local variable first though -- you just pass the name of the array as the parameter: methoTwo(myArray);
. The compiler will automatically convert the name of the array to a pointer to the beginning of the array.
Also note that you can use array-style notation on the receiving end, something like:
localpointer[0] = 1;
localpointer[1] = 2;
...is also reasonable and will accomplish the same as your
*localpointer = 1;
++localpointer;
*localpointer = 2;
For what it's worth, another alternative would be:
*localpointer++ = 1;
*localpointer = 2;
Upvotes: 1