-1

我有一个指针字符数组

void main(){
    char* array[] = 
            {
                    [0] = "foo",
                    [1] = "bar",
                    [2] = "baz"
            };
read(array);
}

并尝试使用获取长度时strlen

int read(const char* events[]){
int size_of_events;
        size_of_events = (strlen(events));
}

它会引发以下警告:

warning: passing argument 1 of ‘strlen’ from incompatible pointer type [enabled by default]
In file included from test.c:6:0:
/usr/include/string.h:395:15: note: expected ‘const char *’ but argument is of type ‘char **’

看不懂是什么问题。。

4

4 回答 4

1

您正在尝试计算strlen非字符串 - 实际上是字符串数组。在传递 a 时strlen将 a作为其参数(一个指向字符数组的指针)。看看会发生什么- 应该返回 3,即.char *char **strlen(events[0])"foo"

于 2013-06-21T14:35:04.760 回答
1

您正在尝试在指针数组上使用字符串函数。

In read(顺便说一下,不要使用 libc 函数名)events的类型是const char **又名指向数组的指针或char *指向 char 的指针。

使用strlen它会产生不可预知的结果。如果幸运的话,它会使您的程序因分段违规而崩溃。

在 C 中,数组在惯性上没有大小或长度。您需要将其作为单独的参数传递给您的函数。

strlen处理(字符数组)的原因char *是因为按照惯例,C 中的字符串由特殊的空终止符符号终止'\0'。它计算直到第一个 '\n' 的字符数量。这不是常规数组的情况。

如果您想要相关字符串的长度,则可以使用strlen(events[0]), strlen(events[1]), strlen(events[2])

于 2013-06-21T14:37:06.463 回答
0

strlen 给出 a 的长度,char*但您正在传递 achar**

我认为你想要你的数组的长度,但你不能拥有它,因为你最后没有 NULL

如果你的数组是这样的:

char* array[] = 
        {
                [0] = "foo",
                [1] = "bar",
                [2] = "baz",
                [3] = NULL,   /* in stdlib.h */
        };

那么你可以去做类似的事情

int read(const char* events[]){
        int size_of_events = 0;
        while (events[size_of_events] != NULL)
            size_of_events++;
        return (size_of_events);
}

如果您的事件数组的大小未知并且您想对其进行计数,则只需NULL在末尾添加然后计数

于 2013-06-21T14:35:19.293 回答
0

您需要传入一个字符串,而不是一串字符串。使用一个字符串的索引而不是 ** 传入一个字符串。

于 2013-06-21T14:36:40.933 回答