Search code examples
carraysstringcharc-strings

How is a pointer to char assigned by a string in C?


I am new to C/C++.

char *x="hello world";
char x[]="hello world";

I know first one is a pointer and second one is a character array.but,I can't understand how char*x works.

int a=1;
int *b=&a;

&a is the memory address.b is the pointer.but,what is the memory address for "hello world".how it apply to x pointer?can anyone explain a little bit?


Solution

  • In C all literal string are stored as non-modifiable (but not constant) arrays of characters, including the null-terminator.

    When you do:

    char *x = "hello world";
    

    you initialize x to point to the first element of such an array (remember that arrays decays to pointers to their first element).

    It's similar to:

    char s[] = "hello world";
    char *x = s;
    

    But with the difference that the string in this example is modifiable.