1

I am trying to create a two dimensional array, which has either 1 or 0 randomly assigned to each coordinate. It works just fine until it gets to the coordinates [20][3]. After that it just throws out "segmentation fault 11".

I am absolutely clueless how or why. Especially since I can create a matrix with 200 * 200 for instance but it still gets the same Problem only at the coordinates [200][3]. So it is somehow always the third y coordinate in the last x coordinate where the error occurs.

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

int main() {

  int x, y, i, j ;
  x = 20;
  y = 20;

  int grid [x][y];

  for ( i = 0; i <= x; i++) {
    for ( j = 0; j <= y; j++) {

      grid[i][j] = rand() % 2 ;

      printf("grid [%d][%d]: %d\n", i, j, grid[i][j]);

    }
  }
  return 0;
}
2
  • There is an error. Your index can only reach 19, you have to change the loops: for ( i = 0; i < x; i++) { // Note the "<" instead "<=" for ( j = 0; j < y; j++) { Commented Sep 5, 2016 at 14:35
  • @Alexi what is that? Commented Sep 5, 2016 at 14:36

2 Answers 2

2

C uses 0-based indexing for arrays. So, for an array defined as

int grid [x][y]

looping for

 for ( i = 0; i <= x; i++) 
   for ( j = 0; j <= y; j++)

if off-by-one. (Note the <= part).

to elaborate, for an array of dimension p, the valid indexes are 0 to p-1, inclusive.

You should change your loop conditions as i < x and j < y to stay withing the bounds. Accessing out of bound memory causes undefined behavior.

That said,

  • int main() should be int main(void), at least, to conform to C standards for hosted environments.
  • There is no need to make grid as VLA here. If the dimensions are already known, better approach is to use a compile-time constant (#define) to generate the array dimensions.
Sign up to request clarification or add additional context in comments.

Comments

2

You're running past the bounds of the array. That's undefined behaviour in C, and is manifesting itself as a crash.

Change i <= x to i < x etc, or increase the grid size.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.