The difference between a pointer-defined string (char*str="hello") and a character array (char str[]={'h','e','l','l','o'})

The difference between a pointer-defined string (char*str="hello") and a character array (char str[]={'h','e','l','l','o'}):
  String An array is an array used to store strings, occupying a continuous unit in memory. The memory occupied is the string. The definition method is: char ch[] can be initialized.
  The character pointer is a pointer to a character, the pointer variable itself is stored on the stack, and the data is stored in the read-only segment, which can only be read and cannot be changed. The definition method is: char *p;
as long as the difference is as follows:
    1) The character array consists of several elements, each element is placed a character, and the address stored in the character pointer variable (the address of the first character of the string) )
    2) Assignment method
      For character arrays, only each element can be assigned, and the following methods cannot be used to assign values ​​to character arrays:
      char str[10];
      str = "hello world!"; Wrong! ! !
      For character pointer variables, the following assignments can be used:
      char *str
      str= "hello world!"; Assign the address of the first element in the string to the pointer variable a.
   3) Initialize
      char *str = "hello world!" ;
      Equivalent to
      char *str=NULL//Prevent wild pointer
      str= "

      char str[10] = {"hello world!"}; can't be written as char str[10]; str = "I love you!";
   4) Define a character array, allocate a memory unit for it at compile time, it has definite address.
      When defining a character pointer variable, a memory unit is allocated to the pointer variable, and the pointer points to the first element of the string.

Guess you like

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