C language basic syntax - string

  1. What is a string

  2. The difference between strings and ordinary character arrays

  3. How to define strings

  4, the use of strings

  5. What is an array of strings

  6. Assignment of string array

  7. Traversal of string array

 

1. What is a string

  • Multiple characters enclosed in double quotes, terminated with '\0'

–"I am a string.\n”
–"a string""other string" ==> "a string other string";

–"a string \

string" ==> "a string string"

 

2. The difference between strings and ordinary character arrays

  • character array

– is an array of character type

– each array element holds one character

  • String

– is a character pointer variable

– Pointer to the address of the first character in the string

  

3. How to define strings

  • Literal "Hello"

printf("Hello");

  • Use character arrays to define arrays

char str[10]={'H','e','l','l','o','\0'};

  • Using character pointers

char* str2 = str;

 

4, the use of strings

  • Variables declared, placed in the stack area in memory.

  • Strings created by literal value are placed in the code area in memory. If a string is created and the value is the same, only one memory area will be created whose value is read-only and the value cannot be changed.

  • Strings created using arrays are placed in the stack area in memory, and multiple identical strings can be created whose values ​​can be changed.

  • A character pointer, which just points to an area of ​​memory.

 

5. What is an array of strings

  • array of pointers (array of strings)

  • The elements in the array are pointers -> pointers are strings -> arrays of strings

  • Save multiple string addresses

 

6. Assignment of string array

int main() {

  //字符串数组
  char* strs[5] = {"aaa", "bbb", "ccc", "ddd", "eee"};

  printf("sizeof(strs[0]=%ld\n",sizeof(strs[0]));

  strs[0] = "AAA";

  return 0;

}

  

7. Traversal of string array

int main()  {

  //字符串数组
  char* strs[5] = {"aaa", "bbb", "ccc", "ddd", "eee"};

  for (int i=0; i<5; i++) {

    printf("%s ", strs[i]);
  } 

  return 0;

}

 

Guess you like

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