【发布时间】:2012-10-22 07:20:58
【问题描述】:
我是 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