-1

When the following program is compiled, I am getting the following error:

error: variable-sized object may not be initialized

What is causing this error?

int loctionofmine[numofmines][2] = {0};
 int numofmines = 3;
    printf("Welcome to minesweeper!\n");
    printf("How many mines? ");
    scanf("%d",&numofmines);
    int i = 0; 
    int loctionofmine[numofmines][2] = {0};   // error is from this statement.
    while(i < numofmines){
        int j = 0;
        while(j < 2){
            scanf("%d",&loctionofmine[i][j]);
            j++;
        }
        i++;
    } 
Richard Chambers
  • 16,643
  • 4
  • 81
  • 106

1 Answers1

0

initialization of an array is done by the compiler at compile time yet you are trying to do it at run time. Since the value of numofmines is read in at run time so the value is unknown to the compiler at compile time, the compiler issues an error.

Richard Chambers
  • 16,643
  • 4
  • 81
  • 106
  • It is not correct that initialization of an array is done by the compiler at compile time. Objects of automatic storage duration generally **cannot** be initialized at compile time because they are created while the program is running, and the number of instances of a particular object (due to recursive calls to a function) generally cannot be predicted. And, while some things can be initialized by the compiler at compile time, others cannot or are not. E.g., the address of a static object may be used as an initializer but cannot be resolved until link time. – Eric Postpischil Mar 12 '20 at 21:27
  • The actual reason the compiler complains about initialization of a variable-size object is this rule in C 2018 6.7.9 3 (or equivalent in whatever specification the compiler is using): “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.” – Eric Postpischil Mar 12 '20 at 21:28