2

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?

blacktrance
  • 905
  • 2
  • 11
  • 25

2 Answers2

5

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

$
Nobilis
  • 7,310
  • 1
  • 33
  • 67
2

Keep iterating until you hit NULL, keeping count.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358