Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C error "variable-sized object may not be initialized" [duplicate]

Tags:

arrays

c

Possible Duplicate:
C compile error: “Variable-sized object may not be initialized”

I've got a problem cause my compiler still gives me an error: Variable-sized object may not be initialized. What's wrong with my code?

int x, y, n, i;
printf ("give me the width of the table \n");
scanf ("%d", &x);
printf ("give me the height of the table\n");
scanf ("%d", &y);
int plansza [x][y] = 0;
int plansza2 [x][y] = 0;

Of course I want to fill the table with 'zeroes'.

Unfortunately the program still doesn't work. The tables are displayed with numbers like '416082' on all of their cells. My code looks like this now.:

int plansza [x][y];
memset(plansza, 0, sizeof plansza);
int plansza2 [x][y];
memset(plansza2, 0, sizeof plansza2);

printf("plansza: \n");
for(j=0;j<x;j++) {
  for(l=0;l<y;l++) {
    printf("%d",plansza[x][y]);
    printf(" ");
  }
  printf("\n");
}

printf("plansza2: \n");
for(m=0;m<x;m++) {
  for(o=0;o<y;o++) {
    printf("%d",plansza2[x][y]);
    printf(" ");
  }
  printf("\n");
}
like image 345
fragon Avatar asked Jun 16 '26 08:06

fragon


1 Answers

Your two arrays are variable lenght arrays. You cannot initialize a variable length array in C.

To set all the int elements of your arrays to 0 you can use the memset function:

memset(plansza, 0, sizeof plansza);

By the way to initialize an array which is not a variable length array, the valid form to initialize all the elements to 0 is:

int array[31][14] = {{0}};  // you need the {}
like image 57
ouah Avatar answered Jun 17 '26 22:06

ouah