How to define strings in the C language?

In the C language, strings can be defined using either character arrays or character pointers.

  1. Define a string using a character array.
char str[100]; // 定义一个字符数组,用于存储字符串
strcpy(str, "Hello, world!"); // 将字符串赋值给字符数组
  1. Define a string using character pointers:
char *str = "Hello, world!"; // 定义一个字符指针,并将字符串赋值给它

When defining a string using a character pointer, the string constant will be stored in a read-only data segment, and the content of the string cannot be modified through the pointer. If you need to modify the string, you can use a character array to store it.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds