How to define a string in C language?

  • In C language, character arrays can be used to define strings.
    For example:
char str[20] = "Hello, world!";

In this example, a character array str with a length of 20 is defined and initialized to the string "Hello, world!".
In C language, a string is a character array ending with \0 (ASCII code is 0), so the length of the character array needs to be 1 more than the length of the string to store the ending \0.

  • In addition, in C language, pointers to characters can also be used to define strings.
    For example:
char *str = "Hello, world!";

In this example, a pointer str to characters is defined and initialized to point to the first character of the string "Hello, world!". This method is equivalent to implicitly defining a character array with a length of 13 and initializing it as "Hello, world!\0".
It should be noted that strings defined in this way are usually 存储在只读内存区域,因此不能通过指针修改字符串的内容.

  • How to modify the string?
char str[20] = "Hello, world!";
str[0] = 'h';
printf("%s", str);  // 输出 "hello, world!"

Guess you like

Origin blog.csdn.net/weixin_42465316/article/details/129457917