Arrays of Strings in C

 

Example #1 –  Simple 2D array of chars

 

#include <stdlib.h>

#include <stdio.h>

#include <string.h>

#define ROWS 3;

#define COLS 5;

 

int main(int argc, char *argv[])

{

char matrix[ROWS][COLS];   

 

         /*

The memory allocated for matrix looks like:

 

matrix: [?][?][?][?][?][?][?][?][?][?][?][?][?][?][?]

0  1  2  3  4  5  6  7  8  9 10 11 12 13 14

 

for convenience we view the matrix as:

         

matrix:     0    1    2    3    4

0 [ ? ][ ? ][ ? ][ ? ][ ? ]

1 [ ? ][ ? ][ ? ][ ? ][ ? ]

2 [ ? ][ ? ][ ? ][ ? ][ ? ]

*/

 

     scanf("%s", matrix[1]); /* assume user types:  cat  */

                

         /*

produces:

        

matrix:     0    1    2    3    4

0 [ ? ][ ? ][ ? ][ ? ][ ? ]

1 ['c']['a']['t']['\0'][ ? ]

2 [ ? ][ ? ][ ? ][ ? ][ ? ]

 

         */

 

 


         strcpy(matrix[2], "dog");

 

/*

produces:

        

matrix:     0    1    2    3    4

0 [ ? ][ ? ][ ? ][ ? ][ ? ]

1 ['c']['a']['t']['\0'][ ? ]

2 ['d']['o']['g']['\0'][ ? ]

         */

 

printf("string in row 1: %s\n", matrix[1]); /* prints cat */

printf("string in row 2: %s\n", matrix[2]); /* prints dog */

 

return 0;

} /* END OF MAIN */

 

 

Question #1:  What if you copy in a string with more than COLS-1 chars ?

 

In this case scanf or strcpy spills the overflow characters into the next row.  If you are already at the last row then you spill over beyond the end of the entire array and you are in an error condition (although you may or may not actually crash).

 

scanf(matrix[0], "foobar");

 

produces:

        

matrix:     0    1    2    3    4

0 ['f']['o']['o']['b']['a']

1 ['r']['\0']['t']['\0'][ ? ]

2 ['d']['o']['g']['\0'][ ? ]

 

Notice that “foobar” spills over to row 1 and overwrites the first 2 chars of the word "cat". This is not a memory access error, since matrix owns the space, but it is probably not a good thing!