Now,from what I understand,the extern
in the declaration of name[]
tells the compiler that its definition is somewhere else (In my program,I have defined it below the part where I have used it).But why then there is different consequence for strlen()
and sizeof
?strlen()
works fine but for sizeof()
I get the error:
invalid application of 'sizeof' to incomplete type 'char[]' |
Here's my program:
#include<stdio.h>
#include<string.h>
extern char name[];
int main()
{
printf("%d,%d",strlen(name),sizeof(name));
}
char name[]="Bryan";
//char name[6]="Bryan"; //Neither of these make sizeof work
I tried to reason it out based on my understanding of the extern
keyword,but I have hit a bottleneck.So please give your answers.
Because sizeof
doesn't know the contents the variable at the point where sizeof
is, but strlen
doesn't care about the compile-time size, it simply walks from the beginning of the string until it finds a NUL character marking the end of the string.
For example:
char name[40] = "Bryan";
...
size_t size = sizeof(name);
size_t len = strlen(name)
strcat(name, " Adams");
printf("%s: len=%zd, size=%zd, strlen(name)=%zd\n",
name, len, size, strlen(name));
This will show
Bryan Adams: len=5, size=40, strlen(name)=11
name
is defined after the function main
, so the compiler cannot tell you what is the size of name
.
sizeof
is an operator that is evaluated at compile-time (except with VLAs), and the symbol name
will be associated with the declaration afterwards, during the linking phase.
One solution is to write the size of the array in the declaration:
extern char name[6];
Then it is your responsibility to make sure that the size is the same in both declaration and definition. A macroconstant would be useful.
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