How to define strings in C programming language?

Strings in C language can be defined using character arrays.

There are two ways to define a string:

  1. Character array: Use a character array to store a string, ensuring that the size of the array is at least one more than the length of the string in order to accommodate the null character at the end. For example, to define a string that contains 11 characters, you can write it like this:
char str[11] = "Hello World";
  1. Character pointer: Use a character pointer to point to the character array storing the string. For example, defining a character pointer pointing to a string can be written like this:
char *str = "Hello World";

It is important to note that if using a character pointer to define a string, it is necessary to ensure that the string the pointer points to is a constant string that cannot be modified. If you need to modify the string, it is recommended to define the string using a character array.

In addition, you can use string functions from the C standard library to manipulate strings, such as strlen(), strcpy(), strcat(), and so on.

bannerAds