Reputation: 269
Why this program only works when I initialize a and b. I want to pass it without initializing a and b, for example:
numChange(10,15);
Is this possible ?
#include <iostream>
using namespace std;
void numChange(int *x,int *y)
{
*x = 99;
*y = 77;
}
int main()
{
numChange(10,15);
//int a=10;
//int b=15;
//numChange(&a,&b);
cout<<a<<" , "<<b<<endl;
return 0;
}
Upvotes: 1
Views: 135
Reputation: 51393
Because you have defined your function to receive pointers, but when you call that function you are trying to pass an int.
The compiler is expecting memory addresses and you are trying to pass constants.
It does not make sense, you are trying to do something like 10 = 99; 15 = 77;?
numChange(10,15);
//int a=10;
//int b=15;
It seems that you are hopping that a = 10 = 99 and b = 15 = 77;
If this was possible, it means that I could never (after the call of numChange(10,15);) make a variable to actually have the value 10 because 10 is "pointing" to 99 (is not).
Upvotes: 3
Reputation: 1640
Recall: a pointer is an integer containing a location in memory.
This:
int a, b;
...
a = b;
copies the integer stored at the memory location reserved for 'b' to the memory location reserved for 'a'.
This:
int *a, b;
...
a = &b;
stores the location of 'b' in 'a'. Following it with this:
*a = 42;
will store 42 in the memory location stored in 'a', which is the variable 'b'.
Now, let's look at your code. This:
void numChange(int *x,int *y)
tells the compiler that 'numChange' will be called with two pointers--that is, memory addresses. This part:
*x = 99;
*y = 77;
then stores two integers at the locations given in 'x' and 'y'.
When you call:
numChange(10,15);
the arguments are integers instead of memory location. However under the hood, memory locations are also integers so the compiler converts the arguments to pointers. Effectively, it's doing this:
numChange((int *)10, (int*)15);
(It should issue a warning when this happens, since it's almost never a good idea, but it will do it.)
Basically, your call to 'numChange' tells it that there are integer variables at memory addresses 10 and 15, and 'numChange' carries on and stores integers at those memory locations. Since there aren't variables (that we know of) at those locations, this code actually overwrites some other data somewhere.
Meanwhile, this code:
int a=10;
int b=15;
numChange(&a,&b);
creates two integer variables and then passes their addresses in memory to 'numChange'. BTW, you don't actually need to initialize them. This works too:
int a, b;
numChange(&a,&b);
What's important is that the variables are created (and the compiler sets aside RAM for them) and that their locations are then passed to 'numChange'.
(One aside: I'm treating variables as always being stored in RAM. It's safe to think of them this way but modern compilers will try to store them in CPU registers as much as possible for performance reasons, copying them back into RAM when needed.)
Upvotes: 2