How to iterate through a char ** pointer?
Let T
be any type. When working on an array of T
of varying size, represented as T*
, you need to specify how the end of such array is represented.
In a simpler case: for a string of characters, i.e. T = char
, the end of array char*
is typically represented by a null character \0
. Thus, you can iterate it as:
char* ptr = myString;
for (char c = *ptr; c; c=*++ptr) {
...
}
You iterate over all characters, until you reach the one that is \0
, making the expression c
evaluate to false
/0
and break the loop.
An alternative representation for a string is to represent the length of the string as a separate number. This is done, for example, in Pascal strings.
int size = myStringSize;
for (int idx=0; idx<size; ++idx) {
char c = myString[idx];
}
Either of the approaches can also be used when you have an array of strings (i.e. T = char*
). Your options are:
- You store a special non-string value in your
enjoy
array set toNULL
at the end of the array - Or you store the total size of the
enjoy
array in a separate value.
You can also use both options -- this is the case, for example, with arguments given to int main(int argc, char** argv)
. The argc
stores the number of string values in the argv
, and argv[argc]
is guaranteed to be NULL
.
If you use the first option you would then iterate it as:
char** ptr = enjoy;
for (char* c = *ptr; c; c=*++ptr) {
...
}
and if you use the second option:
int size = enjoySize;
for (int idx=0; idx<size; ++idx) {
char* str = enjoy[idx];
}
Notice the similarity of these snippets iterating over char**
, to those used for iterating over a simple char*
.
Note that a value NULL
stored in the enjoy
array is different than storing a pointer to an empty string. The latter should not be used as a marker for the end of the array, because it can lead to hard-to-track bugs when a legitimate empty-string value is added to your enjoy
array.
Comments
-
optimus prime over 3 years
I have the following code
struct my_struct { const char **enjoy; }; const char * enjy[] = { "Cricket", "movie", "", "Ball", "eat", "", }; static const struct my_struct my_struct_table[1] = { [0] = { .enjoy = enjy } };
Now I want to use that final structure and want to iterate using that. How can I iterate using
my_struct_table[0].enjoy
I want to print all the strings in the
enjy
variable.