4

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.

Thokchom
  • 1,602
  • 3
  • 17
  • 32

2 Answers2

5

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
Mats Petersson
  • 126,704
  • 14
  • 140
  • 227
3

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.

md5
  • 23,373
  • 3
  • 44
  • 93
  • Just make sure you don't "fool" the compiler by using one size in the extern declaration and another in the actual variable definition - that will lead to "interesting" problems. – Mats Petersson May 11 '13 at 18:41