Array of strings example in C
Arrays of strings are useful when we need to read and process text files line by line. This article explains how to use arrays of strings in C and provides a simple working example.
Example using array of strings
The following example reads a file into an array of strings
#include <stdio.h> #include <malloc.h> #include <string.h> #define MAXLINES 256 int main () { char **array; /* Array of strings */ char line[256]; int i=0, num=0; FILE *fp; array = calloc (MAXLINES, 256); if ((fp = fopen ("/path/to/file", "rb")) == NULL) { fprintf (stderr, "unable to open file\n"); return (1); } while ((fgets (line, 256, fp) != NULL) && (i < MAXLINES)) { array[i] = (char*) malloc(strlen (line) + 1); strncpy (array[i], line, 256); i++; } num = i; array[num] = NULL; i=0; while (i<num) { printf ("Line %d : %s ", i, array[i]); i++; } /* Free the array of strings after use */ free(array); return (0); }
| Labels: coding, howto |
|

Comment