Can I initialize an array in the header?

So, I am making a program. And by the start I've got an error. If I do this:

#include <stdio.h>

int k[5];
k[0] = 1;

int main ()
{
 printf("hello world %d",k[0]);
}

I get the following errors:

4   [Warning] data definition has no type or storage class
4   [Warning] type defaults to 'int' in declaration of 'k'
4   [Error] conflicting types for 'k'
3   [Note] previous declaration of 'k' was here
4   [Error] invalid initializer

I can only think the problem is the compiler, because, well, an array is not that hard to use, I guess. Can anybody see what the problem is?

Upvotes: 0

Views: 278

Answers (1)

John Bode
John Bode

Reputation: 123458

You cannot have statements such as k[0] = 1; outside the body of a function. What you can do is use an initializer when you declare the array:

int k[5] = {1, 0, 0, 0, 0};

or

int k[5] = {1};

or

int k[5] = {[0] = 1};

which all ultimately have the same affect. If you have fewer items in the initializer than there are elements in the array, the elements that aren't explicitly initialized are initialized to 0 or NULL, depending on the type.

Upvotes: 3

Related Questions