Reputation: 1052
I have a char* array that looks like this:
{"12", "34", "", 0}
I'm passing it to a function, so it decays to a pointer. So I have a function that takes in a char**, and within the function I want to iterate through the array until I find the zero, at which point I want to stop. I also want to know how many strings there are in the array. What is the best way of going about this?
Upvotes: 2
Views: 4055
Reputation: 7458
Maybe something like this can help:
#include <stdio.h>
void foo(char** input) /* define the function */
{
int count = 0;
char** temp = input; /* assign a pointer temp that we will use for the iteration */
while(*temp != NULL) /* while the value contained in the first level of temp is not NULL */
{
printf("%s\n", *temp++); /* print the value and increment the pointer to the next cell */
count++;
}
printf("Count is %d\n", count);
}
int main()
{
char* cont[] = {"12", "34", "", 0}; /* one way to declare your container */
foo(cont);
return 0;
}
In my case it prints:
$ ./a.out
12
34
$
Upvotes: 5
Reputation: 799560
Keep iterating until you hit NULL
, keeping count.
Upvotes: 2