How do you define strings in the C language?

In the C language, strings can be defined in the following ways:

  1. Character Array: Character arrays can be used to store and represent strings. For example:
char str[] = "Hello, world!";

The variable “str” here is an array of characters that contains the string “Hello, world!”. It is important to note that a null character (‘\0’) will automatically be added at the end of the character array to signify the end of the string.

  1. Character pointer: Strings can also be defined using character pointers. For example:
char *str = "Hello, world!";

The variable ‘str’ here is a character pointer that points to the first address of the string “Hello, world!”. It is important to note that strings defined using character pointers are immutable (i.e. constant strings).

  1. Dynamic memory allocation allows for the dynamic allocation of memory at runtime to store strings. For example:
char *str = malloc(sizeof(char) * (length + 1));
strcpy(str, "Hello, world!");

Here, the malloc() function is used to allocate enough memory space, and the strcpy() function is used to copy the string “Hello, world!” into the dynamically allocated memory. Don’t forget to use the free() function to release the memory after using the string.

It is important to note that when defining a string using the above method, you need to include the string.h header file to use related string operation functions (such as strcpy()).

bannerAds