When using the address transfer of function, View address blocks of formal parameters and actual parameters, I find that the arguments and formal parameters of array share one address block, while the arguments and formal parameters of variables use two address block. What is the reason?
The code is as follows:
#include<iostream>
using namespace std;
void test(int *i,int * arr) {
cout << &i << endl;
cout << arr << endl;
}
int main() {
int i = 1, arr[2] = {1,2};
cout << &i << endl;
test(&i, arr);
cout << arr << endl;
system("pause");
return 0;
}
And this is the output:
0000008986B6FC54
0000008986B6FC30
0000008986B6FC78 //Arrays use the same space
0000008986B6FC78
CodePudding user response:
You are passing pointers to the functions. The value of the pointers are not modified, ie in the function they point to the same objects as they do in main.
However, you are not printing what you think you print:
void test(int *i,int * arr) {
cout << &i << endl;
cout << arr << endl;
}
The pointer i
gets the parameter &i
(the i
from main). Hence printing i
in main will yield the same value as printing i
in test
. However, you are printing the adress of i
in the function not the value of it. If you change your code to:
void test(int *i,int * arr) {
cout << &i << endl;
cout << i << endl;
cout << arr << endl;
}
You will notice the difference. I suggest you to rename at least one of the i
s in your code, because using same name for different entities can and does cause confusion. The i
in test
holds the value of the address of the i
in main
. That does not mean that they are the same, but rather i
in test
has the same value as &i
in main
.
In short: &i == &i
but you expect &(&i)
to be the same as &i
.
There is no difference between passing a pointer to the int
or passing a pointer to the first element of the array. From the point of view of the function they are both just pointers to int
.
CodePudding user response:
Note that test
prints the value of arr
but the location of i
.
In test
, &i
is the location of its argument i
.
That argument's value is the location of the i
in main
.
You will see this if you print i
instead of &i
.
arr
, on the other hand, is implicitly converted into a pointer to its first element, and you are both passing &arr[0]
to test
to print, and printing &arr[0]
in main
.
Here is the same thing with explicit conversions and without using a function:
int main() {
int i = 1, arr[2] = {1,2};
cout << &i << endl;
// Create the "argument"...
int *p = &i;
// These two lines are 'test'...
cout << &p << endl;
cout << &arr[0] << endl;
// and this is after the function call.
cout << &arr[0] << endl;
}