0

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?

  • 3
    "*I can only think the problem is the compiler*". Very very unlikely and not a conclusion you should ever jump to. 99% of the time the problem is in your code. The `k[0]= 1;` doesn't do what you think it does. Non-initializer assignments are not permitted outside a function. Remove that line and change the line before it to be `int k[5] = {1};`. – kaylum Oct 17 '21 at 19:45
  • 2
    This would also work: `int k[] = {1,0,0,0,0};` – selbie Oct 17 '21 at 19:48
  • I also like `int k[] = {1,};`, because it makes more clear that the very first element is being explicitly initialized. – Jardel Lucca Oct 17 '21 at 19:53
  • @selbie strongly consider adding `static`. Otherwise one will problems with multiple definitions – tstanisl Oct 17 '21 at 19:59
  • @tstanisl - agree. – selbie Oct 17 '21 at 21:07
  • I knew there were many ways to declare arrays, I was just wondering the reason why that exact code didn't work. I mean, it does the same. – Ica Polinesio GarLop Oct 18 '21 at 00:31

1 Answers1

3

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.

John Bode
  • 119,563
  • 19
  • 122
  • 198
  • If the array is going to be used in `const` mode I suggest using `static` to avoid multiple definition when the header is included from multiple translation units – tstanisl Oct 17 '21 at 20:18