0

I need to let the user enter an integer N which will become the size of the array. I tired the following:

int N;

printf("Please enter size of array\n");
scanf("%d", &N);

int a[N] = {0};

However i get the following error when I do this:

error: variable-sized object may not be initialized

Anyone know how can do this? Any help would be greatly appreciated!

4 Answers4

1

You need to use a dynamically allocated array.

int N;

printf("Please enter size of array\n");
scanf("%d", &N);

int *a = malloc(N * sizeof(int));

Then you can access it like a normal array.

Edit: in C99 the compiler allows dynamic length arrays, so you can just use memset or do a for loop going through the array and setting the value for each index

mthandr
  • 3,062
  • 2
  • 23
  • 33
  • 2
    He doesn't actually *need* to use a dynamically allocted array. C99 allowes and defines the use of [variable-length arrays](http://en.wikipedia.org/wiki/Variable-length_array) and since the compiler doesn't complain about the vla it seems to be operating at at least C99 levels. Additionally your answer doesn't address the problem of initializing the array. – Kninnug Nov 27 '14 at 18:17
  • 1
    You can simply replace malloc with calloc to initialize the array to zero. – Etheryte Nov 27 '14 at 18:27
  • Thanks a lot! Worked perfectly! – user3261286 Nov 27 '14 at 18:35
1

You may not initialize variable length arrays.

From the C Standard (6.7.9 Initialization)

3 The type of the entity to be initialized shall be an array of unknown size or a complete object type that is not a variable length array type.

So write simply

int a[N];

instead of

int a[N] = {0};

If you need to initialize the array with zeroes then you can use standard function memset declared in header <string.h>

#include <string.h>

//...

memset( a, 0, sizeof( a ) );
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
1

Just like the error says: you may not initialize a variable sized object (like that). You need to either set the individual elements in a loop, or use memset:

for(size_t i = 0; i < N; i++){
    a[i] = 0;
}

or:

memset(a, 0, sizeof a);

Note that memset requires you to include <string.h>

EDIT: sizeof a is shorter and looks better :)

Kninnug
  • 7,992
  • 1
  • 30
  • 42
0

Try this:

int N;

printf("Please enter size of array\n");

scanf("%d", &N);

int a[N];

a[0] = 0;