C - Use two-dimensional char array to represent string array

Description

Use two-dimensional char array to represent string array

Demo

#include <stdio.h> 

#define SIZE 3 /*from ww w  .  ja  va  2s  .co m*/

int main() 
{ 
      char president[SIZE][8] = { 
          "test", 
          "test1", 
          "test2" 
      }; 
      int x,index; 

      for(x=0;x<SIZE;x++) 
      { 
          index = 0; 
          while(president[x][index] != '\0') 
          { 
              putchar(president[x][index]); 
              index++; 
          } 
          putchar('\n'); 
      } 
      return(0); 
}

Result

The code above declares a two-dimensional char array: president.

The first value in square brackets is the number of items (strings) in the array.

The second value in square brackets is the maximum size required to hold the largest string.

Because all items in the array's second dimension must have the same number of elements, all strings are stored using eight characters.

Related Topic