c - 在输出数组编号的同时枚举C中的数组

标签 c arrays enumerate

我试图在 C 中枚举一个数组(就像在 python 中您可以使用 #enumerate 函数一样)。

static enumerate(const char *data[])
{
    int i;
    int stopLength = sizeof(data);
    for(i=0; i < stopLength; i++)
    {
        printf("[%d] %s", i+1, data[i]);
    }
}

int main(int argc, char *argv[])
{
    char *friends[] = {"test", "test", "test"};
    enumerate(friends);
}

但是,当我尝试使用此功能时,出现以下错误:

utilis.c: In function ‘int enumerate(char**)’:
utilis.c:58:33: warning: ‘sizeof’ on array function parameter ‘data’ will return size of ‘char**’ [-Wsizeof-array-argument]
     int stopLength = sizeof(data);
                                 ^
utilis.c:55:29: note: declared here
 static enumerate(char *data[])
                             ^
utilis.c: In function ‘int main(int, char**)’:
utilis.c:78:46: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]
     char *friends[] = {"test", "test", "Test"};
                                              ^
utilis.c:78:46: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]
utilis.c:78:46: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]

我明白错误告诉我的是什么,但我不明白如何实现我想做的事情。在 python 中,我可以这样做:

friends = ["test", "test", "test"]
for i, f in enumerate(friends, start=1):
    print "[{}] {}".format(i, f)

# [1] test
# [2] test
# [3] test

如何让我的 C 函数按照我想要的方式运行?

最佳答案

因为它是一个函数参数,所以数组被调整为指向第一个元素的指针。在您的例子中,指向数组中第一个指针的指针。您不能对其使用 sizeof,因为那只会产生指针的大小,这没有用。相反,您需要将数组的大小传递给函数:

static void enumerate(size_t size, const char *data[size])
{
    int i;
    size_t stopLength = size;
    ...

来电者:

enumerate(sizeof(array)/sizeof(*array), array);

关于c - 在输出数组编号的同时枚举C中的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43071431/

相关文章:

python - 从多维 Numpy 数组中减去平均值

python - 在 cython 中迭代数组,列表是否比 np.array 更快?

c - 开启环回后如何收到消息?

c - 在 C 中,如何在共享库文件中使用主程序文件中的函数

Java:求二维数组的总和

c - 用 C 语言枚举注册表项及其数据

wpf - 枚举嵌入资源目录中的文件

C Pipe() 和 fork()

javascript - C - tiny-aes-c 和 Javascript CryptoJS 互操作性

python - enumerate 是否创建其参数的副本?