How to Declare an Array of Strings in C

Ok, I know this is not a big deal, I just hate to deal with strings in C, so I’ll put the code here so I can copy-paste-modify whenever I need to do such things.

Purpose: declare an array of strings.

There are two cases here:

First case: You know the number of strings (say NUM_OF_STRINGS), and all strings have the same length – including the terminating ‘\0′ character – (say LENGTH_OF_STRING).

In this case, this is how the array can be declared:

1
2
3
4
5
char* arrayOfStrings[NUM_OF_STRINGS];
for (i = 0; i < NUM_OF_STRINGS; i ++) {
        if (! (arrayOfStrings[i] = (char*)malloc(LENGTH_OF_STRING * sizeof(char))))
                  exit(-1);
};

Second case: Number of strings and length of each string is know only in runtime. In this case your code should look like this:

1
2
3
4
5
6
7
8
9
10
char** arrayOfStrings;
int nStrings = GetNumberOfStrings();
int i;
if (! (arrayOfStrings = (char**) malloc(nStrings * sizeof(char*)))
        exit(-1);
for (i = 0; i < nStrings; i ++) {
        int strLen = GetStringLength(); /* Length includes terminating '\0' char */
        if (! (arrayOfStrings[i] = (char*) malloc(strLen * sizeof(char)))
               exit(-1);
};

That’s it. Don’t forget to free the allocated memory when you’re done.


If you enjoyed this post, make sure you subscribe to my RSS feed!

Post to Twitter Post to Delicious Post to Digg Post to Facebook Post to Reddit Post to StumbleUpon

Related posts:

  1. Array Indexing in C
  2. Make Shell Scripts Executable By Default

Tags:

Friday, November 28th, 2008 Programming

Leave a Reply

my email
my photo
Hi,
My name is Amir Watad. I have a BSc. in biomedical engineering from The Biomedical Engineering school , Technion , Israel, and a BSc. in electrical engineering from The Electrical Engineering school , Technion , Israel.
I'm a Verification Engineer in Mellanox Technologies Ltd.
I love Linux, the Command Line and the OpenSource Community.
I used to write Poems (Arabic) when I was able to find time for this.
November 2008
S M T W T F S
« Oct   Dec »
 1
2345678
9101112131415
16171819202122
23242526272829
30  
SEO Powered by Platinum SEO from Techblissonline

Twitter links powered by Tweet This v1.6.1, a WordPress plugin for Twitter.