Difference between initializing C-style string to NULL and empty string

Are these three equivalents:

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

      

I suspect the former is different from the others, but I'm not entirely sure.

+3


source to share


3 answers


char* p = NULL;

      

This assigns NULL to the pointer p

, which means it p

does not point to any valid memory address.



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

      

They create blank lines and are mostly equivalent. q

points to a valid memory address, unlike p

in the previous example. r

- an array with an empty string.

+2


source


I am in charge of C ++, although the OP has also tagged a C question as well. They are two different languages. It is not good to combine them.

This declaration:

char* q = "";

      

used a legacy conversion in C ++ 03 and was invalidated in C ++ 11. We are now in C ++ 14.


These two announcements:



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

      

fundamentally different. The first one declares a pointerand sets it to null. The second one declares an array one element that is set to null.


Relatively

" Are these three equivalent

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

+5


source


char* p= NULL; // initializes the character pointer to NULL
char* q = ""; // character pointer points to a valid string with null content
char r[] = {'\0'}; // character array having null content

      

+1


source







All Articles