Home > Software engineering >  What is/are the difference(s) between the two following variables? (Except their names)
What is/are the difference(s) between the two following variables? (Except their names)

Time:03-23

char *s1 = "";

char *s2 = NULL;

I just want to know the difference

CodePudding user response:

One is pointing to the first element of an array of a single char element, the element being the string null-terminator character '\0'.

The other variable is initialized point to NULL which means it doesn't point anywhere, really.


Slightly simplified, the definition

char *s1 = "";

is kind of equivalent to

char private_array[1] = { '\0' };
char *s1 = &private_array[0];

It might seem confusing to have both a string null terminator, and a generic null pointer, but it will clear itself out with more experience.

Also note that in C all literal strings (even "") are not modifiable, they are in essence read only. That's why it's recommended to always use const char * to point to literal strings.

CodePudding user response:

There's a very big differnce using "" leaves '\0', whereas NULL leaves the pointer as ((void *)0).

This can be tested via dereferencing the pointer like:

NOTE: Dereferencing the pointer means accessing its inner values or elements, which is done using * unary operator or [] operator in C/C .

""

#include <stdio.h>

int main(void){
    char *s1 = "";
    printf("%d", *s1);
    return 0;
}

I'm printing the integer representation of *s1 because '\0' can't be seen on the terminal.

Ouput:

0

And program returned 0 which means success.

NULL

#include <stdio.h>

int main(void){
    char *s2 = NULL;
    printf("%d", *s2);
    return 0;
}

The above program printed nothing on stdout, but it returned 139, which means program crashed before it exited (segmentation fault).

You can try it online.

CodePudding user response:

An empty string has a single element, the null character, '\0'. That’s still a character, and the string has a length of zero, but it’s not the same as a NULL, which has no characters at all.

  •  Tags:  
  • c
  • Related