Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop Through Strings in char**

Tags:

arrays

c

pointers

I have a function with the following signature:

void foo (char **bar);

'bar' is an array of strings with an unknown length.

I need to write a loop checking if every string in 'bar' holds some property, without knowing how many elements are in this array.

I've seen multiple articles saying that this is easy if my signature is either of the following:

void foo (char *bar[LENGTH]);
void foo (char bar[LENGTH01][LENGTH02]);

EDIT: My original question had both of these signatures not contain a hash-defined length, they have been added for clarity.

(I could get the length of the above through sizeof(bar)/sizeof(bar[0])).

Unfortunately, the signature of this function is already defined, and I can't modify it.

Is it still possible to create (for example) a for loop which goes through each string of this array, or is this impossible?

like image 842
Jinan Dangor Avatar asked Jul 17 '26 19:07

Jinan Dangor


1 Answers

While you can check when a single string ends ( for example bar[0] ) by looking at the string terminator \0 or using strlen function, you cannot check where the array of strings ends. Unless the last one has been initialized with NULL.

In that case you can write:

char* str;
int i = 0;
while ((str = bar[i]) != NULL){
    printf("%s\n",str);
    i++;
}
like image 93
Tony Barletta Avatar answered Jul 20 '26 08:07

Tony Barletta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!