Why does the lack of an array index in "extern char name []" not affect strlen (name) but cause an error for sizeof (name)?

Now, from what I understand, extern in the name[] declaration tells the compiler that its definition is somewhere else (in my program, I defined it below the part where I used it). But why then there are different consequences for strlen() and sizeof ? strlen() works fine, but for sizeof() I get an error:

invalid application of 'sizeof' to incomplete type 'char[]' |

Here is 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 explain this based on my understanding of the extern keyword, but I got into a bottleneck. So please give your answers.

+4
source share
2 answers

Since sizeof does not know the contents of the variable at the point where sizeof , but strlen does not care about the size of the compilation time, it just goes from the beginning of the line until it finds the NUL character denoting the end of the line.

For instance:

  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)); 

It will show

 Bryan Adams: len=5, size=40, strlen(name)=11 
+5
source

name defined after the main function, so the compiler cannot tell you what the size of name .

sizeof is a statement that is computed at compile time (with the exception of the VLA), and the name character will be associated with the declaration afterwards during the bind phase.

One solution is to write the size of the array in the declaration:

 extern char name[6]; 

Then you are responsible for ensuring that the size is the same both in the ad and in the definition. A macro constant would be helpful.

+3
source

Source: https://habr.com/ru/post/1480279/


All Articles