How to define and assign values to a string array in the C language?

In C language, string arrays can be defined and assigned values in the following way:

  1. Define a string array variable: You can use a two-dimensional array of char type to define a string array variable. For example, char strArray[5][20]; defines an array containing 5 strings, with a maximum length of 20 characters for each string.
  2. Assigning a single string directly: You can use the strcpy() function to directly assign a string to a specific element in a string array. For example, strcpy(strArray[0], “Hello”); will assign the string “Hello” to the first element in strArray.
  3. Assigning strings one by one: You can use a for loop to assign each element in a string array individually. For example,
for (int i = 0; i < 5; i++) {
    printf("Enter a string: ");
    scanf("%s", strArray[i]);
}

The code example above will read 5 strings from standard input one by one and assign each of them to an element in the strArray array.

It is important to note that when assigning string arrays, ensure that the target string array has enough length to accommodate the string to be assigned. Also, if intending to use string arrays, pay attention to adding the terminating character ‘\0’.

bannerAds