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