Software Development

Array of Strings in C

Array of Strings in C
Written by admin


In C programming String is a 1-D array of characters and is outlined as an array of characters. However an array of strings in C is a two-dimensional array of character sorts. Every String is terminated with a null character (). It’s an utility of a 2nd array.

Syntax:

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

Right here,

  • var_name is the identify of the variable in C.
  • r is the utmost variety of string values that may be saved in a string array.
  • c is a most variety of character values that may be saved in every string array.

Instance: 

C

#embrace <stdio.h>

  

int most important()

{

  char arr[3][10] = {"Geek"

                     "Geeks", "Geekfor"};

  printf("String array Components are:n");

    

  for (int i = 0; i < 3; i++) 

  {

    printf("%sn", arr[i]);

  }

  return 0;

}

Output

String array Components are:
Geek
Geeks
Geekfor

Beneath is the Illustration of the above program 

Memory Representation of Array of Strings

 

We now have 3 rows and 10 columns laid out in our Array of String however due to prespecifying, the dimensions of the array of strings the area consumption is excessive. So, to keep away from excessive area consumption in our program we are able to use an Array of Pointers in C.

Invalid Operations in Arrays of Strings 

We are able to’t straight change or assign the values to an array of strings in C.

Instance:

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

Right here, arr[0] = “GFG”; // This may give an Error which says task to expression with an array sort.

To alter values we are able to use strcpy() perform in C

stcpy(arr[0],"GFG"); // This may copy the worth to the arr[0].

Array of Pointers of Strings

In C we are able to use an Array of pointers. As an alternative of getting a 2-Dimensional character array, we are able to have a single-dimensional array of Pointers. Right here pointer to the primary character of the string literal is saved.

Syntax:

char *arr[] = { "Geek", "Geeks", "Geekfor" };
Array of Pointers of Strings

 

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

C

#embrace <stdio.h>

  

int most important()

{

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

  printf("String array Components are:n");

    

  for (int i = 0; i < 3; i++) 

  {

    printf("%sn", arr[i]);

  }

  return 0;

}

Output

String array Components are:
Geek
Geeks
Geekfor

About the author

admin

Leave a Comment