Click to See Complete Forum and Search --> : Counting number of strings in an array of strings?
endoalpha
05-23-2007, 06:18 PM
I am working on a program in C that has dynamic char** arrays. I know how many strings are in the array initially, but after adding and removing strings, how do I know how many are in there? How can I count how many rows are in this char** array?
Thanks
bwkaz
05-23-2007, 06:32 PM
You can't.
A "char**" is a pointer to a pointer (or in your case, it's a pointer to the first of a list of pointers). You can't tell how many pointers there are, for the same reason you can't tell the size of a random buffer that you've been given a pointer to. The memory's not "tagged" like that, and even if it was, C doesn't have any "length of an array" operators.
To find out how long an array is, you have to do one of two things. First, you can keep track of how many items you add and remove, and therefore keep the count in a separate variable. Second, you can make sure the last array element is always a NULL pointer (and none of the pointers before the last one are NULL); then you can iterate through the array until you get to a NULL pointer. But there's no guarantee that the last element is always NULL; you have to keep it that way yourself.
endoalpha
05-23-2007, 06:39 PM
I was afraid of that. :(
I new I should have used a linked list instead. Array of strings, silly me.
Modorf
05-24-2007, 04:34 PM
alternatively,
you can migrate your code to c++ and use STD::Vectors<strings>, which takes care of the array length management for you.