• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

How can I pass an array to a function & then change the original array?

mulder

Senior member
Maybe I have forgotten something that's easy to do or not, but I am having trouble getting one of my functions to work. Basically I am creating an array of 8 values. I am then passing that array, the size, and one more parameter to second function. That second function proceeds to recurse itself, whiles at each recursive call inserts a new value into the array -- it presently doesn't return anything. I want to change the original array values. Are you following me? However, the original array nevers changes. So, I did some reading and I found out when you pass something to a function it justs creates a copy in that new function. I need to know how to pass an array and change the original values of that array in the new function. Is it possible?

Just in case your want to know what I am doing...I am working with a tree to generate a pre-order traversal. I need each node in the tree to be inserted into an array in that order. That's why the second function is a recursive function. I am starting with the root node and working my way through the tree's descendants.

Please help, because I don't know what else to do. Thanks.
 
In C++, arrays are automatically passed by referenece, which means when you modify them in a function the actual array is being modifed. So by default arrays are NOT passed in as copies.

In other words your array should be changing when you modify it. Show us the source code to the bits that deal with the array and double check that the array isn't changing.
 
Another way is to pass a pointer to that array, instead of trying to pass the array... this way in your second function you can access the array using the pointer...
 
Another way is to pass a pointer to that array, instead of trying to pass the array

That's what already happens by default. It's the pointer to the array that's being passed in to the function.

For example an array:

char array [100];

makes no difference if a function takes it as

void function (char array []) or
void function (char *array).

They both mean exactly the same thing and are both call-by-reference.
 
Back
Top