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.
Related posts:
Leave a Reply
About Me
Tags
Categories
- Algorithms
- Bash
- BlackBerry
- Collaboration
- Command Line
- Cool Tricks
- Easter Eggs
- Ebooks
- Firefox
- Hardware
- Humor
- iPhone
- Linux
- Linux Development
- Linux Kernel
- Networks
- Open Knowledge
- Other
- Productivity
- Programming
- Regular Expressions
- Science
- Security
- Shell Scripts
- Short Posts
- Social Networks
- Thoughts
- Tools
- Vim
- Web Development
- Websites
Popular Posts
Calendar
Archives
- July 2010 (5)
- June 2010 (1)
- May 2010 (1)
- April 2010 (3)
- March 2010 (1)
- January 2010 (1)
- December 2009 (2)
- September 2009 (13)
- July 2009 (1)
- June 2009 (6)
- May 2009 (4)
- March 2009 (18)
- February 2009 (10)
- January 2009 (10)
- December 2008 (7)
- November 2008 (8)
- October 2008 (1)
- August 2008 (1)
- July 2008 (1)
- June 2008 (2)
