How to define a string in the C language?

In C language, a string can be defined using a character array. For example:

char str[] = "Hello, World!";

The code above creates a character array called str and assigns the string “Hello, World!” to it. It is important to note that the size of the character array will automatically adjust based on the length of the string. Alternatively, you can specify the size of the character array explicitly, for example:

char str[20] = "Hello, World!";

The character array str defined in this way has 20 elements, including all the characters of the string and an additional element for storing the string termination character \0.

Additionally, you can use pointers to define a string, for example:

char *str = "Hello, World!";

The code above defines a pointer variable str pointing to characters, and assigns the address of the string “Hello, World!” to it. Strings defined in this way exist in memory as constants and cannot be modified. If the content of the string needs to be changed, it can be defined using character arrays.

Leave a Reply 0

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


广告
Closing in 10 seconds
bannerAds