Alex Rivera | Logout

External Delaration for An Array?

Asked 2010-06-18T17:36:42.853
28

I have an array defined in a file and in another I have to use it, for e.g-

/* a.c - defines an array */

int a[] = {1,2,3,4,5,6,7,8,9}; 


/* b.c - declare and use it. */

#define COUNT ((sizeof a)/(sizeof int))
extern int a[];  //size of array

.
.
.

int i;
for(i=0; i<COUNT; i++)
  printf("%d", a[i]);
.
.
.

Now when I try to compile it it gave me error saying that sizeof cann't be used on incomplete type.

Can anybody tell me how to handle such case in C/C++? I don't want to array subscript in a.c

Thanks in advance

c
Edit
Report

1 Answer

29

You might put something like the following into a.c and then extern it from b.c.

In a.c:

int a[] = {1, 2, 3};
const int lengthofa = sizeof( a ) / sizeof( a[0] );

And then in b.c:

extern int a[];
// the extern (thanks Tim Post) declaration means the actual storage is in another 
// module and fixed up at link time.  The const (thanks Jens Gustedt) prevents it
// from being modified at runtime (and thus rendering it incorrect).
extern const int lengthofa;

void somefunc() {
  int i;
  for ( i = 0; i < lengthofa; i++ )
    printf( "%d\n", a[i] );
}
answered 2010-06-18T17:50:41.977

Your Answer