5

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?

Community
  • 1
  • 1
mko
  • 21,334
  • 49
  • 130
  • 191
  • Other than all the other answers you've got that point out the problems, I'd recommend you to not redefine functions from the standard library. Invent new names, it's safer. – Art Oct 22 '12 at 07:30
  • for the sake of this duplicate question while i don't think its duplicate but concludes the same basic idea, the answer should be as many has mentioned this array will eventually happen to be a pointer which you don't want to get the size of directly instead you need to reference it using sizeof &source on that line. – Waheed Jun 28 '19 at 07:46

3 Answers3

11

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.

alestanis
  • 21,519
  • 4
  • 48
  • 67
9

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.

Fred Foo
  • 355,277
  • 75
  • 744
  • 836
1

The size of the array doesn't follow when you pass it to the function. Actually it's passed as a pointer which is why the warning message mentions

will return size of 'const char *'

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621