Open In App

Array of Strings in C

In C programming String is a 1-D array of characters and is defined as an array of characters. But an array of strings in C is a two-dimensional array of character types. Each String is terminated with a null character (\0). It is an application of a 2d array.

Syntax:



char variable_name[r] = {list of string};

Here,

Example: 






// C Program to print Array
// of strings
#include <stdio.h>
 
// Driver code
int main()
{
  char arr[3][10] = {"Geek",
                     "Geeks", "Geekfor"};
  printf("String array Elements are:\n");
   
  for (int i = 0; i < 3; i++)
  {
    printf("%s\n", arr[i]);
  }
  return 0;
}

Output
String array Elements are:
Geek
Geeks
Geekfor

Below is the Representation of the above program 

 

We have 3 rows and 10 columns specified in our Array of String but because of prespecifying, the size of the array of strings the space consumption is high. So, to avoid high space consumption in our program we can use an Array of Pointers in C.

Invalid Operations in Arrays of Strings 

We can’t directly change or assign the values to an array of strings in C.

Example:

char arr[3][10] = {"Geek", "Geeks", "Geekfor"};

Here, arr[0] = “GFG”; // This will give an Error that says assignment to expression with an array type.

To change values we can use strcpy() function in C

strcpy(arr[0],"GFG"); // This will copy the value to the arr[0].

Array of Pointers of Strings

In C we can use an Array of pointers. Instead of having a 2-Dimensional character array, we can have a single-dimensional array of Pointers. Here pointer to the first character of the string literal is stored.

Syntax:

char *arr[] = { "Geek", "Geeks", "Geekfor" };

 

Below is the C program to print an array of pointers:




// C Program to print Array
// of Pointers
#include <stdio.h>
 
// Driver code
int main()
{
  char *arr[] = {"Geek", "Geeks", "Geekfor"};
  printf("String array Elements are:\n");
   
  for (int i = 0; i < 3; i++)
  {
    printf("%s\n", arr[i]);
  }
  return 0;
}

Output
String array Elements are:
Geek
Geeks
Geekfor

Article Tags :