Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between initializing a C-style string to NULL vs. the empty string

Tags:

c++

c

string

Are these three equivalent:

char* p= NULL;
char* q = "";
char r[] = {'\0'};

I suspect the first one is different from the rest, but I'm not entirely sure.

like image 232
dfg Avatar asked Oct 26 '14 05:10

dfg


2 Answers

I'm answering for C++ even though the OP has also tagged the question as C. These are two different languages. It's not a good idea to conflate them.

This declaration:

char* q = "";

used a deprecated conversion in C++03, and became invalid in C++11. We're now at C++14.


These two declarations:

char* p= NULL;
char r[] = {'\0'};

are fundamentally different. The first declares a pointer and sets it null. The second declares an array of one item, which item is set to null.


Regarding

Are these three equivalent

the answer is no, not at all: one is just invalid, one declares a pointer, one declares an array.

like image 87
Cheers and hth. - Alf Avatar answered Sep 28 '22 11:09

Cheers and hth. - Alf


char* p = NULL;

This assigns NULL to the pointer p which means that p does not point to any valid memory address.

char* q = "";
char r[] = {'\0'};

These both create empty strings and are basically equivalent. q points to a valid memory address, unlike p in the previous example. r is an array with an empty string.

like image 35
Code-Apprentice Avatar answered Sep 28 '22 12:09

Code-Apprentice