0

I'm trying to create an array with dimension n in a function, i don't get why the compiler gives me this error:

error: variable-sized object may not be initialized

warning: excess elements in array initializer

The code is the following, the program isn't of course finished since I can't get this to work, and it gives me the same error in similar projects:

    #include <stdio.h>
#include <stdlib.h>

//given a number, find all binary numbers with that number of digits
int gen_num(int);
int main()
{
    int n;
    printf("Insert a number: ");
    scanf("%d",&n);
    gen_num(n);
    return 0;
}

int gen_num(int n){

    int num[n]={0};
    return 0;
}

If I try to not initialize in the declaration, but I for example try to ask the user to input some values it gives me the same error, since the array is created with dimension 0

Thanks in advance

  • Tip: When you get an error just paste it directly into your favourite search engine as the minimum research to do before posting a question. – kaylum Nov 26 '20 at 10:40
  • Tip: Reverse the order of these definitions and you won't need the pretty much useless declaration at the top. In C code it's pretty much expected that you write your precursor functions first, then have main at or near the end. – tadman Nov 26 '20 at 10:41
  • Problem is that I'm using 2011 C so this shoudn't occur, and I've always used this notation and never had problems – Sebastian Cordero Nov 26 '20 at 10:43
  • 1
    C11 6.7.9/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**." (emphasis mine). – Ian Abbott Nov 26 '20 at 10:49
  • 1
    What notation are you referring to? If you mean VLA (Variable Length Array), `int num[n]`, that's not the problem. The problem is the initialiser which is not allowed for VLAs. – kaylum Nov 26 '20 at 10:50

2 Answers2

0

Use calloc() to allocate and initiate arrays dynamically.

int gen_num(int n){
    int *num = calloc(n, sizeof(int));

    /* treat 'num' like an array of integers */
    num[3] = 3;
    
    free(num); 
    return 0;
}

If you only call gen_num() once, you don't have to call free(), you can let the memory leak. But call free() anyway, it's a good habit.

Another way is

int num[n];
memset(num, 0, sizeof(int) * n);
mr. fixit
  • 1,404
  • 11
  • 19
0

If you really mean to use a dynamically sized array (C99), then by definition the size of the array is not known at compile-time, thus the initializer syntax won't work. You have to explicitly initialize (using e.g. a for-loop or memset()).

S.C. Madsen
  • 5,100
  • 5
  • 32
  • 50