Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make C++ pointers null [closed]

Tags:

c++

pointers

While declaring all c++ pointer, all should by default be initilized to ZERO or NULL to avoid any random unwanted values. So that we can check if pointer is null that means not initilized.

thanks

like image 606
Vijay Avatar asked Mar 24 '11 05:03

Vijay


People also ask

How do I make my pointer point null?

We can use nullptr to explicitly initialize or assign a pointer a null value. In the above example, we use assignment to set the value of ptr2 to nullptr , making ptr2 a null pointer. Use nullptr when you need a null pointer literal for initialization, assignment, or passing a null pointer to a function.

Can pointer be null in C?

A null pointer is a pointer which points nothing. Some uses of the null pointer are: a) To initialize a pointer variable when that pointer variable isn't assigned any valid memory address yet. b) To pass a null pointer to a function argument when we don't want to pass any valid memory address.

Does freeing a pointer set it to null?

free() is a library function, which varies as one changes the platform, so you should not expect that after passing pointer to this function and after freeing memory, this pointer will be set to NULL.

Can you free a null pointer in C?

It is safe to free a null pointer. The C Standard specifies that free(NULL) has no effect: The free function causes the space pointed to by ptr to be deallocated, that is, made available for further allocation.


2 Answers

In C++03, prefer ptr = 0 over ptr = NULL (Bjarne S. says that. Read the excerpt below quoted from his site)

In C++0x, ptr = nullptr (see this)


Bjarne Stroustrup says that,

Should I use NULL or 0?

In C++, the definition of NULL is 0, so there is only an aesthetic difference. I prefer to avoid macros, so I use 0. Another problem with NULL is that people sometimes mistakenly believe that it is different from 0 and/or not an integer. In pre-standard code, NULL was/is sometimes defined to something unsuitable and therefore had/has to be avoided. That's less common these days.

If you have to name the null pointer, call it nullptr; that's what it's going to be called in C++0x. Then, "nullptr" will be a keyword.

like image 168
Nawaz Avatar answered Sep 28 '22 07:09

Nawaz


void * ptr = NULL;

or

void * ptr = 0;
like image 20
Alex Deem Avatar answered Sep 28 '22 09:09

Alex Deem