testing how to pass values/references/pointers

Jul 30, 2014 at 2:22pm
Getting error c2664 passbypointer
cannot convert parameter 1 from 'int' to 'int *'
Please explain what this means.
And how to fix it thank you.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
 #include <iostream>
using namespace std;
void passbyvalue(int);
void passbyreference(int &);
void passbypointer(int *);
void main()
{
	int x = 7;

	cout << x <<endl;
	passbyvalue(x);
	passbyreference(x);
	passbypointer(x);
	system("pause");
};
void passbyvalue(int x)
{
	x = x + 2;
	cout << x <<endl;
}
void passbyreference(int &x)
{
	x = x + 2;
	cout << x <<endl;
}
void passbypointer(int *x)
{
	x = x + 2;
	cout << x <<endl;
}
Last edited on Jul 30, 2014 at 2:22pm
Jul 30, 2014 at 2:34pm
Line 13: You're trying to pass an int, not a pointer to an int.

Should be:
 
  passbypointer(&x);


Jul 30, 2014 at 2:43pm
Thank you for the explanation.
Jul 30, 2014 at 2:50pm
Remember that a pointer doesn't point to any literals exactly, it points to the memory address of the variable in question.

If you tried to run that program now, the "passbypointer" member function would display the memory address of the variable "x" instead of the data held by the variable "x". You need to de-reference "x".

You can de-reference variables by placing an asterisk (*) before the variable.

1
2
3
4
5
void passbypointer(int *x)
{
	*x += 2; // if we didn't dereference this statement, it would add 2 to the memory address.
	cout << *x << endl;
}


1
2
3
4
5
6
int x = 5;
int* bob = &x;

cout << x; // this would display "x" which the value is "5".
cout << bob; // this would display the memory address of "x".
cout <<*bob; // this would display "x" which the value is "5". 


Also the return type for main should be "int" not "void".
Last edited on Jul 30, 2014 at 3:03pm
Topic archived. No new replies allowed.