Reputation: 43
I'm trying to program up a 2D dynamically allocated array for a map for a small game. Below is my code, I'm unsure why int* array[yCoord] is throwing up the error that it cannot be a variable length array, as the variable yCoord is assigned a specific value in the main function below. Any help greatly appreciated.
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include"random.h"
void createMap(int xCoord, int yCoord) {
int i, j;
xCoord += 2;
yCoord += 2;
int* array[yCoord];
for (i = 0; i < yCoord; i++) {
array[i] = (int*)malloc(xCoord * sizeof(int));
}
for (i = 0; i < yCoord; i++) {
for (j = 0; j < xCoord; j++) {
array[i][j] = 0;
}
}
}
int main(void) {
int x, y;
x = 5;
y = 5;
createMap(x, y);
return 0;
}
Upvotes: 1
Views: 151
Reputation: 213892
int* array[yCoord];
is a variable-length array (VLA) since the dimension is determined in run-time based on another variable. And in this case also highly questionable since that array will only exist inside that function, you can't return it to the caller. Also please note that bad teachers/books have a habit of teaching you how to malloc 2D arrays incorrectly - Correctly allocating multi-dimensional arrays (please share with your teacher if they don't know this).
VLA were introduced to the C language in the year 1999. So if you are using a compiler older than 23 years, or explicitly telling one to compile using an obsolete version of the language, the code won't compile. Hence "ISO C90 forbids variable length (C89/C90)" - your compiler is using the long-since obsolete version of C from 1989.
I would strongly recommend to upgrade to a compiler from this millennium. In case of old versions of gcc, it means executing them correctly since it defaulted to C90 (or rather "GNU90") all the way to version 5.0.0. See What compiler options are recommended for beginners learning C? As noted there, the -ansi
switch is harmful, since it does not mean "strict standard compliance" but rather "standard compliance against ANSI/ISO 1989". Switch -ansi
for -std=c99
, -std=c11
or -std=c17
(the current version of C).
Upvotes: 1