我得到了这个警告:数组函数参数上的sizeof将返回'const char *'的大小而不是'const char []'

时间:2012-10-22 07:20:59

标签: c

  

可能重复:
  Why sizeof(param_array) is the size of pointer?

我是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 个答案:

答案 0 :(得分:7)

此警告告诉您,如果您致电sizeof(char[]),您将无法获得数组的大小,但会获得char*指针的大小。

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

答案 1 :(得分:6)

那是因为const char source[]在参数位置只是const char *source的语法糖。例如,参见Steven Summit's C notes

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

答案 2 :(得分:0)

答案 3 :(得分:0)

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

  

将返回'const char *'

的大小