Possible Duplicate:
Why sizeof(param_array) is the size of pointer?
I'm new to C, I got an warning from clang
when compiling my code:
#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;
}
I don't know what does the following warning mean:
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[]) {
Any idea?
This warning is telling you that if you call sizeof(char[])
you won't get the size of the array but the size of a char*
pointer.
This means that your variable size_of_array
will be wrong because it won't represent the size of the real array.
That's because const char source[]
in argument position is just syntactic sugar for const char *source
. See, e.g., Steven Summit's C notes.
In this particular case, you'll want to call strlen
. When not dealing with strings, pass the size of the array as a separate argument.
I think you're looking for this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With