Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I got this warning: sizeof on array function parameter will return size of 'const char *' instead of 'const char []' [duplicate]

Tags:

c

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?

like image 430
mko Avatar asked Oct 22 '12 07:10

mko


3 Answers

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.

like image 107
alestanis Avatar answered Nov 03 '22 00:11

alestanis


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.

like image 22
Fred Foo Avatar answered Nov 02 '22 23:11

Fred Foo


I think you're looking for this.

like image 41
johnwbyrd Avatar answered Nov 03 '22 00:11

johnwbyrd