I cant print b :(Code:void function(int & i)
{
i=5;
}
int main()
{
int a=2;
int *b=&a;
function(b);
printf(b);
return 1;
}
Printable View
I cant print b :(Code:void function(int & i)
{
i=5;
}
int main()
{
int a=2;
int *b=&a;
function(b);
printf(b);
return 1;
}
The function is expecting a reference to an int, but you are passing it an int* instead.
Thank you
I fix it this way
An error has reported,Code:#include <iostream>
using namespace std;
void function(int & i)
{
i=5;
}
int main()
{
int a=2;
int *b=&a;
function(&b);
cout<<b;
return 1;
}
#include <iostream>
using namespace std;
void function(int* i)
{
*i=5;
}
int main()
{
int a=2;
int *b=&a;
function(b);
cout<<*b;
return 1;
}
Look at these lines
In the second line you take a pointer to the object a by preceding the variable with an ampersand. In the third line you take a pointer to the object b. Since b has type int*, &b has type int** (pointer to pointer to int). If instead you want to take get the value of what b points to, use *b.Code:int a=2;
int *b=&a;
function(&b);
Also, here
you are printing the value of b, i.e. the memory address it is pointing to. You can get the value of what b is pointing to in the same way as above.Code:cout<<b;
Thanks
@chandrasekaran1987..... but I don't want to change it into pointer (in the function) :(
@D_Drmmr..... Can you write it for me please ?
Why use a pointer at all? What's wrong with
If you really want the pointer in mainCode:#include <iostream>
using namespace std;
void function(int& i)
{
i=5;
}
int main()
{
int a=2;
function(a);
cout<< a;
return 1;
}
Code:#include <iostream>
using namespace std;
void function(int& i)
{
i=5;
}
int main()
{
int a=2;
int* b = &a;
function(*b);
cout<< *b;
return 1;
}
I could, but I generally don't do that since I don't believe it will help you. If you want to see an example then search for one online and you'll find plenty. Then again, I can't imagine that the book you are studying (or your teacher) didn't provide any examples that show how to dereference a pointer. Reapplying that knowledge in another situation is what learning is all about. If you just copy a piece of code written by someone else, you have learned nothing - and that will come to haunt you for sure.