My code is

int null = 0;
int *p = null;

It gives me an error: cannot initialize a variable of type 'int *' with an lvalue of type 'int'.

In C it would work.

EDIT:

How can I make it work in this spirit?

It's from an exercise (2.32) from the Primer C++ book:

Is the following code legal or not? If not, how might you make it legal?

int null = 0, *p = null;
有帮助吗?

解决方案

If you are using C++11 then use nullptr:

int *p = nullptr;

If you are not using C++11 then use NULL instead:

int *p = NULL;

Do not define your own null value at all, since C/C++ already has one of its own. NULL has no type, it is simply defined as 0, and an integer literal 0 can be assigned to a pointer:

int *p = 0;

其他提示

change int *p = null; to int *p = (int*)null;

You should use nullptr in C++11. C++ doesn't do automatic conversion between int and x* (where x is type), so using an int typed variable to define null won't work. In pre-C++11, you can use integral literals, like 0. (You can still use integral constants after the new standard, but there are good reasons for using nullptr over NULL. What are the advantages of using nullptr?)

You can read more about it nullptr here: http://en.cppreference.com/w/cpp/language/nullptr.

I think *p is not a correct identifier for C. this is because a good identifier shouldn't start with a symbol but a letter.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top