tags:

views:

52

answers:

4

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

+5  A: 

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] );
}
Mark Wilkins
+1, but explaining the use of `extern` would be helpful to the OP.
Tim Post
you also should give sizeofa a const attribute
Jens Gustedt
@Tim and @Jens: Thanks - good points. I made some edits.
Mark Wilkins
A: 

The compiler does not have enough information when compiling b.c to determine the size of the array. That information is only in a.c where your initializer list is in scope.

You will have to communicate the size somehow. One method is to define an int const with the size and extern that as well. Another possibility would be to use a sentinel (a value outside your valid data range) to indicate the end of the array.

Amardeep
A: 

in my opinion if you don't have definition and define with sizeof a in one file it doesn't compile.

Files are compile and stored as *.obj / *.a files. You can use arrays from another files thanks to extern declaration which will be check in linking process, after compilation.

You want to declare define (preprocesor must help here with this. It is run before compilator).

so before compilation you won't get array from another file...

noisy
+2  A: 

If you want your array size to be accessible as a compile-time constant, then you have no other choice but to specify array size explicitly in the extern declaration of the array

extern int a[9];

In this case it becomes your responsibility to make sure that array size is consistent between the extern declaration and definition. You can use a manifest constant for that, but still it is going to be your responsibility to make sure that the number of initializers between the {} and the declared size are the same.

If you don't care to have the array size as a compile-time constant, then you can do what Mark Wilkins suggests in his answer.

AndreyT