c - 遍历末尾为零的字符串数组

标签 c arrays string pointers char

我有一个 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/

相关文章:

c - GNU gdb 如何显示源文件名和符号行

string - 字符串长度是否等于字节大小?

c - 注意 c 中字符串的奇怪行为

c - socket函数中的stream参数和protocol参数有什么区别?

c - "Can' t 打开输出文件“scanf 调用时出错

c - 构建库时遇到问题

java - 通过数组进行索引循环并打印出元素?

php - fatal error : Uncaught exception 'PDOException' : Invalid parameter number: parameter was not defined' on the execution of my $params array

Java 重置和复制二维数组

c - strstr() 函数类似,忽略大写或小写