Understanding of char pointer initialization in C language

char pointer, that is, char * type. Its initialization is essentially no different from the initialization of other variables, that is, to give it an initialized value. 
For a pointer, in the C language, it is an address. Distinguish the initialization situation, there are four appearances:
1 Initialization is empty. That is , in the form of
char * str = NULL;,
NULL is a specific null pointer in C language, and its value is 0. In C language, using NULL as an invalid state of the pointer itself is an illegal address value.

2 Initialized to a constant string address.
char * str = "test"; The
constant string will be placed in the constant space at runtime, so after initialization, the address is an address in the constant space, and this address can only be read, not written. That is, the value of str can be changed, but the value pointed to by str cannot be modified.
In the C language, a string is a continuous character, but for "hello", the "hello" here is equivalent to the array name, so even if you see printf ("%c", "hello[2]); It's not surprising to use it. It is equivalent to char a[10]="hello",printf ("%c",a[2]); 
In short, remember that the entire string is written out in the compiler equivalent to the array name .But the only difference between him and the array is that he is read-only. It cannot be changed through the pointer. For example, char *p="hello", p[2]='y', wrong! The string is read-only and cannot be changed. But arrays can be changed.


3 Initialized to variable address. The variable addresses here include global variables, addresses of local variables, and memory addresses
applied for through dynamic allocation .
In this case, the space pointed to by the pointer can be modified.

4 Do not initialize.
This situation is allowed in C language. If it is a global variable or a static local variable, the system defaults to 0, that is, NULL. And for local variables, it will be a random value. So if the local variable is not initialized, you must assign a legal value to it before taking the value it points to, otherwise the access will go wrong.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325214183&siteId=291194637