user12593879
user12593879

Reputation:

Declaring and later defining an array in C

Edit: I would like to ask the question differently;

Why would this produce a compile time error:

int a[];

int main(){
    a[] = {1, 2, 3};
}

How else can it be done? Above works if a[] = {1, 2, 3}; is defined globally like this:

int a[];
a[] = {1, 2, 3};

int main(){
    //
}

Old question:

Assume the following:

test1.h

void init();
int a[];

test1.c

#include <stdio.h>
#include "test1.h"

int a[] = {6};
int main()
{
    init();
    return 0;
}

test2.c

#include "test1.h"

void init()
{
    printf("%d\n", sizeof(a));
    printf("%d\n", a[0]);
}

Above will have this compile time error: error: invalid application of 'sizeof' to an incomplete type 'int []'

However, printf("%d\n", a[0]); will print 6 just fine. Why sizeof cannot be used with this way of declaring arrays?

Upvotes: 0

Views: 76

Answers (1)

ikegami
ikegami

Reputation: 385829

Why would this produce a compile time error:

The compiler needs to know how much memory to reserve for an array in static storage at compile time, so it can't depend on code in functions.

Why sizeof cannot be used with this way of declaring arrays?

First of all, int a[]; should be extern int a[]; in test1.h.

The size of the array is set by int a[] = {6};, which is found in a file compiled completely independently, and thus not available when requested by sizeof.

The size isn't needed for a[0] since no bound checks are performed.

Upvotes: 3

Related Questions