Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is absence of array index in "extern char name[]" not affecting strlen(name) but causing error for sizeof(name)?

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.

like image 500
Thokchom Avatar asked Feb 17 '23 13:02

Thokchom


2 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
like image 188
Mats Petersson Avatar answered Feb 22 '23 23:02

Mats Petersson


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.

like image 38
md5 Avatar answered Feb 23 '23 01:02

md5