Functions

Hi all,

I wrote this small piece of code, after executing the code I had this output:

Inside the function: 2
Outside the function: 2

This is not what I expected. I would like to have my "test" array untouched by the function div2. I expected the fucniton div2 just copying the array "test" to "test2" without changing its content.

Is this possible? What am I doing wrong?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
void div2(int test2[2])
{
test2[0]/=2;
test2[1]/=2;
cout << "Inside the function: " << test2[0] << endl;
return;
}

int main(int argc,char *argv[])
{
int test[2];
test[0]=4;
test[1]=2;
div2(test);
cout << "Outside the function: " << test[0] << endl;
getchar();
return 1;
}

When you pass array to a function as a parameter what you're really passing is a pointer to the first element of a original array. You can make a copy of array in that function and work with a copy if you don't want to change original array.
http://c-faq.com/aryptr/aryptrparam.html
Last edited on
Topic archived. No new replies allowed.