How can a string be defined in the C language?

In C language, a string can be defined using a character array. The specific steps are as follows:

  1. Define a character array variable to store the characters of a string.
  2. Use square brackets after the array variable name and specify the length of the array to accommodate the number of characters in the string (including the string terminator ‘\0’).
  3. Enclose the contents of the string in double quotes after the equal sign and assign it to an array variable.

The example code is shown below:

char str[10] = "Hello";

The code above defines a character array str with a length of 10. This array can store a string of 5 characters (‘H’, ‘e’, ‘l’, ‘l’, ‘o’), as well as a string termination character ‘\0’. It is important to note that the length of the array needs to be one more than the actual number of characters in the string to accommodate the string termination character.

Leave a Reply 0

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


广告
Closing in 10 seconds
bannerAds