C ++ pointer initialization summary and pointer initialization Summary
1.Character pointer Initialization
In C, "string" stores the address of the first character. Therefore, you can assign the string constant "string" to the pointer char * p;
char *s ="123456";
P = "string", but the string constant cannot be directly assigned to the array,
char ch1[10];ch1="123456";
Strcpy is required.
Strcpy_s (secure, "123456"); // VS2012 is used by strcpy_s. It is a secure version of strcpy.
However, you can initialize the array as a string, that is, a character array. For example, char str [] = "string ";
Differences between the two initialization methods:
char * p="the fine day" ;char str[]="the fine day"
Different, the two are initialization for the string. The former only gives the first address of the string to str, and does not allocate enough memory address to save the entire string, save them in the array, that is, allocate the memory required by all characters. Therefore:
(1) char * p = "string"; // the address Variable p stores the 's' address, and (2) char str [] = "the fine day "; // the str array stores the entire string, which degrades to pointer (3) char * str1 = "the day"; // OK.
In this case, if you want to copy another string str1 to p or str:
Strcpy (p, str1); // error! You need to change it to p = (char *) malloc (strlen (str1) + 1); then the strcpy (str, str1) is correct; // No error, there is enough memory, but it cannot always be guaranteed. Strncpy (str, str1, strlen (str); // correct! Not discussed
In fact, (1) is incorrect, as if an error has been reported for the new standard;
Normally, the initialization should be as follows: strcpy (p, "string ");
Or change to: const * p = "" string "; but you cannot modify p.
A new version of strcpy_s has been released to address the problem that overflow caused by insufficient allocated memory space. For details, refer to other logs.
In addition, this error occurs during initialization.
Char * p = 'a'; // the pointer can only store the address, not the saved value (character)
2. Integer pointer Initialization
Which of the following statements can print the output?
Int a = 10; int * p1 = 0; int * p2 = & a; // common, initialized as the address of a variable int * p3 = 20; printf ("p1 = % p, * p1 = % d \ n", p1, * p1); printf ("p2 = % p, * p2 = % d \ n ", p2, * p2); printf ("p3 = % p, * p3 = % d \ n", p3, * p3 );
When these statements are compiled, a warning is displayed: the row p3 assigns an integer to the pointer without type conversion.
Running will cause a crash.
Why?
Take a closer look, int * p1 = 0; // is it initialized?
Int * p3 = 20; // * Is p3 initialized to 20?
In fact, int * p1 = 0 is equivalent to int * p1 = NULL. The NULL pointer p1 and * p1 values cannot be read !, No error is reported during compilation, but an exception is reported during runtime.
Int * p3 = 20 is equivalent to int * p3; p3 = (int *) 0x00000014; * p3 value cannot be read.