I'm just learning to use pointers. Here is a simple code to illustrate the problem that I am having. I'm getting the following error message:
error C2664: 'triple_it' : cannot convert parameter 1 from 'int **' to 'int *'
Here is the code. Can anybody "point" me in the right direction? (sorry).
#include "stdafx.h"
#include <iostream>
using namespace std;
void triple_it(int *p);
int main(array<System::String ^> ^args)
{
int n = 30;
int *p;
cout << "You have entered " << n << endl;
triple_it(&p);
cout << n << " is 3x the number you entered." << endl;
You're getting that error because you're trying to pass triple_it the address of the pointer, not the address the pointer is storing.
Also, your pointer isn't being assigned an address (presumably n).
Imagine it like this:
1 2 3 4 5 6 7
int x = 5;
int *ptr;
ptr = &x; // ptr assigned address of x
cout << ptr << endl; // Output is the memory address of x
cout << *ptr << endl; // Output is the value of x (5)
cout << &ptr << endl; // Output is the memory address of ptr
Thanks. I think that I understand what you are saying. So, when I call the function, I should just pass p (not &p), right?
When I do this, however, my program errors at run-time "An unhandled exception of type 'System.NullReferenceException' occurred" in the function at the line
*p = *p *3
What am I missing? Sorry to be so dense. Thanks for your help.
Thank you, though. Now I understand the role of the ampersand - to pass along the address. The fundamental error that I made in my initial code was that when calling the function triple_it, I should have been passing &n (the address of n) instead of &p (the address of the pointer). I just didn't understand what the ampersand was doing. Now, thanks to your reply, I do (I hope).
// Pass by pointer
void FuncA(int *ptr)
{
*ptr += 5;
}
// Pass by reference
void FuncB(int &val)
{
val += 10;
}
int main()
{
int x = 10;
int *ptr = &x;
// Send pointer to FuncA
FuncA(ptr);
cout << x << endl; // 15
// Send address of x to FuncA
FuncA(&x);
cout << x << endl; // 20
// Send x to FuncB which references x
FuncB(x);
cout << x << endl; // 30
// De-reference the pointer and send that to FuncB,
// which references what was de-referenced.
FuncB(*ptr);
cout << x << endl; // 40
return 0;
}
(You probably won't ever really use the last example) If you want to read more on this, just look for 'Pass by pointer' and 'Pass by reference'
Also, just so you might use it in the future: x += 5 is the same as x = x + 5.