5

可能重复:
为什么 sizeof(param_array) 是指针的大小?

我是 C 新手,clang编译代码时收到警告:

#include<stdio.h>

char *strcpy (char destination[],const char source[]);
int main(void) {
    char str1[] = "this is a very long string";
    char str2[] = "this is a short string";
    strcpy(str2, str1);
    puts(str2);
    return 0;
}
char *strcpy (char destination[], const char source[]) {
    int size_of_array = sizeof source / sizeof source[0];
    for (int i = 0; i < size_of_array; i++) {
        destination[i] = source[i];
    }
    return destination;
}

我不知道以下警告是什么意思:

string_copy_withou_pointer.c:12:29: warning: sizeof on array function parameter
      will return size of 'const char *' instead of 'const char []'
      [-Wsizeof-array-argument]
        int size_of_array = sizeof source / sizeof source[0];
                                   ^
string_copy_withou_pointer.c:11:46: note: declared here
char *strcpy (char destination[], const char source[]) {

任何的想法?

4

4 回答 4

10

这个警告告诉你,如果你打电话sizeof(char[]),你不会得到数组的大小,而是char*指针的大小。

这意味着您的变量size_of_array将是错误的,因为它不会代表真实数组的大小。

于 2012-10-22T07:24:49.250 回答
8

那是因为const char source[]in argument position 只是const char *source. 例如,参见Steven Summit 的 C 笔记

在这种特殊情况下,您需要调用strlen. 当不处理字符串时,将数组的大小作为单独的参数传递。

于 2012-10-22T07:23:57.603 回答
1

我想你正在寻找这个。

于 2012-10-22T07:23:38.117 回答
1

将数组传递给函数时,数组的大小不会跟随。实际上它是作为指针传递的,这就是警告消息提到的原因

将返回 'const char *' 的大小

于 2012-10-22T07:25:25.840 回答