What is this error for my C ++ program?
I wrote the program below to set a value (here it is 3
) to some place in memory that is pointed by a named pointer using a named p
function f()
and print it to main
:
#include <iostream>
using namespace std;
void f(float* q)
{
q=new float;
*q=3;
}
int main()
{
float *p= nullptr;
f(p);
cout<<*p;
return 0;
}
But when I want to compile it I get this compile time error:
ap1019@sharifvm:~$ g++ myt.cpp
myt.cpp: In function âint main()â:
myt.cpp:12:11: error: ânullptrâ was not declared in this scope
float *p=nullptr;
^
ap1019@sharifvm:~$
What's wrong?
source to share
It seems that the literal pointer is nullptr
not supported by your compiler. You can use a null pointer constant instead. for example
float *p = 0;
But your program is wrong anyway. It has a memory leak because you are storing the address of the allocated memory in a local variable of the function f
, which will be destroyed after the function exits.
The program might look like this
#include <iostream>
using namespace std;
void f( float **q)
{
*q = new float;
**q = 3;
}
int main()
{
float *p = 0;
f( &p );
cout << *p;
delete p;
return 0;
}
Or you can use a pointer link. for example
#include <iostream>
using namespace std;
void f( float * &q)
{
q = new float;
*q = 3;
}
int main()
{
float *p = 0;
f( p );
cout << *p;
delete p;
return 0;
}
source to share