我有一个 char* 数组,如下所示:
{"12", "34", "", 0}
我将它传递给一个函数,因此它会衰减为一个指针。所以我有一个接受 char** 的函数,在函数中我想遍历数组直到找到零,此时我想停止。我还想知道数组中有多少个字符串。解决这个问题的最佳方法是什么?
最佳答案
也许这样的事情可以帮助:
#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;
}
在我的例子中它打印:
$ ./a.out
12
34
$
关于c - 遍历末尾为零的字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17101684/