1. initialization of character pointers
In C, "string" is the address where the first character is located so you can assign the string constant "string" to the pointer char *p;
char *s ="123456";
P= "string" but cannot assign string constants directly to an array,
Char ch1[];ch1="123456";
Need to use strcpy.
strcpy_s (CH1,"123456"); // VS2012 with strcpy_s, it's strcpy's safe version.
But you can initialize an array to a string, that is, a character. such as char str[] = "string";
The difference between the two types of initialization:
Char * p="ThefineDay" ; Char str[]="ThefineDay"
, these two are the initialization of the string, the former just give the first address of the string to STR, not allocate enough memory address to save the whole string, the latter, while initializing, save them in the array, that is, allocating all the characters required memory. So:
(1) Char " string "; // The address variable p holds the address of ' s ' , (2) Char " The fine Day "; // The character Array Str holds the entire string, and in some cases degrades to a pointer (3) Char " the day "; // OK.
At this point, if you want to copy another string str1 to P or str:
strcpy (P, str1); // Error! need to be changed to p= (char*) malloc (strlen (STR1) +1); Only correct strcpy (str, str1); // no errors, there is enough memory, but not always guaranteed. strncpy (str, STR1, strlen (str)); // Right! Not for discussion
In fact, (1) is wrong, as if the new standard has been error;
Typically this should be initialized: strcpy (P, "string");
or instead: const *P = "string"; However, you cannot modify p.
The memory space allocated for this may be insufficient to cause an overflow of unsafe issues, and a new version of strcpy_s has been developed. Refer to other logs for details.
In addition, this initializes the wrong
char *p ='a'; // pointers can only save addresses, not saved values (character a)
2. Initialization of shaping pointers
Let's try the following statement which line can print output?
intA =Ten;int* P1 =0; int* P2 = &a;//Common, initialized to the address of a variableint* P3 = -; printf ("p1=%p, *p1=%d\n", p1, *p1);p rintf ("p2=%p, *p2=%d\n", p2, *p2);p rintf ("p3=%p, *p3=%d\n", p3, *P3);
These lines of statements compile with a warning: The P3 line assigns integers to pointers, not type conversions.
The run-time causes a crash.
Why is it?
Take a closer look, int * p1 = 0; Is it really initialized?
int * P3 = 20; *P3 initialized to 20?
In fact int *p1 = 0 equals int *p1 = NULL, cannot read null pointer p1 and *P1 value! , the compilation will not error, but the runtime will report an exception.
and int *p3 = 20 is equivalent to int *p3; P3 = (int *) 0x00000014; The value of the *P3 cannot be read.
Summary of C + + pointer initialization