0

I'm trying to fill an array with numbers from 1-100 with this code:

#include <stdio.h>

int main()
{
    int num[100];
    int i = 0;

    for (i = 0; i < 100; i++)
    {
        int num[i] = i+1;
    }
}

but I'm getting this error:

c:18:13: error: variable-sized object may not be initialized

I'm still relatively new to programming so I'm not sure what this means. Can you tell me?

dreamcrash
  • 47,137
  • 25
  • 94
  • 117
user1850397
  • 35
  • 1
  • 2
  • 3
    Being new to programming doesn't mean you can skip searching the internet before asking. Stackoverflow itself suggests taking a look at the [this](http://stackoverflow.com/q/11562642/912144), [this](http://stackoverflow.com/q/3082914/912144) and many others answering your question. – Shahbaz Nov 25 '12 at 00:38

3 Answers3

4

Replace this

 int num[i] = i+1;

For this:

 num[i] = i+1;

You already declare the array on the top int num[100];

First you declare the array, and then you iterate over it inside the loop.

Since you are new, it is preferable you start by reading a good book about the subject my recommendation.

dreamcrash
  • 47,137
  • 25
  • 94
  • 117
2

The problem is the int in int num[i] = i+1. The compiler thinks you're trying to declare a new array (also called num) with i elements in it (that's the variable-sized object part). Just remove the int from that line.

melpomene
  • 84,125
  • 8
  • 85
  • 148
0

You are declaring the array again in the loop:

int num[i] = i+1;

Anyway, this is the error in your code but the problem for the compiler is not there: it gives you that error because that's not a valid declaration with initialization for an array. If you just write int num[i]; the code it's valid code and it will compile without error (well, only from C99, old C89 doesn't support variable-length arrays). This is what the compiler recognizes and tries to report.

effeffe
  • 2,821
  • 3
  • 21
  • 44