【问题标题】:I got this warning: sizeof on array function parameter will return size of 'const char *' instead of 'const char []' [duplicate]我收到了这个警告:数组函数参数上的 sizeof 将返回 'const char *' 而不是 'const char []' [重复]
【发布时间】:2012-10-22 07:20:58
【问题描述】:

可能重复:
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[]) {

有什么想法吗?

【问题讨论】:

  • 除了指出问题的所有其他答案外,我建议您不要重新定义标准库中的函数。发明新名字,这样更安全。
  • 为了这个重复的问题,虽然我不认为它重复但得出相同的基本思想,但答案应该与许多人提到的一样,这个数组最终会碰巧是一个你不知道的指针'不想直接获取大小,而是需要在该行上使用 sizeof &source 来引用它。

标签: c


【解决方案1】:

此警告告诉您,如果您调用 sizeof(char[]),您将不会获得数组的大小,而是获得 char* 指针的大小。

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

【讨论】:

  • 那要怎么修呢?
  • 要修复它,你可以使用strlen函数。
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:
    【解决方案4】:

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

    将返回'const char *'的大小

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-11-13
      • 1970-01-01
      • 1970-01-01
      • 2013-12-20
      • 2019-01-31
      • 2012-05-26
      • 1970-01-01
      相关资源
      最近更新 更多