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?

+3


source to share


3 answers


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;
}

      

+2


source


nullptr

only supported with gcc-4.6 or later.

You can work around this easily with const void *nullptr=(void*)0;

, but to avoid later gcc update issues, I suggest



  • update your gcc (4.6 is pretty old)
  • or not to use it.

This is just syntactic sugar, you don't need that.

+1


source


The word null is not reserved by the C ++ standard.

Use NULL instead.

-1


source







All Articles