How to initialize a string in the C programming language?

In the C language, there are several ways to initialize strings:

  1. Initialize a string using a character array.
char str[] = "Hello World";
  1. Initialize a string using character pointers.
char *str = "Hello World";
  1. Initialize the string character by character.
char str[12];
str[0] = 'H';
str[1] = 'e';
str[2] = 'l';
str[3] = 'l';
str[4] = 'o';
str[5] = ' ';
str[6] = 'W';
str[7] = 'o';
str[8] = 'r';
str[9] = 'l';
str[10] = 'd';
str[11] = '\0';
  1. copy a string
#include <string.h>

char str[12];
strcpy(str, "Hello World");

It is important to note that when initializing a string using a character pointer, the string constant pointed to is read-only and cannot be modified. However, when initializing a string using a character array, the elements of the array can be modified.

bannerAds