Popular matrix in C

Asked

Viewed 80 times

0

I have a problem I can’t solve, I believe it’s a very primary mistake.

I need to popular a matrix (i,j), however, when I have the matrix printed, it gives a Bus error or Segmentation fault.

Look at the code below:

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

#define LINHAS 8
#define COLUNAS 10

int main(){
  double matrizA[LINHAS][COLUNAS];
  srand(time(NULL));

  for(int i = 1; i <= LINHAS; i++){
    printf("Valor de I: %d\n", i);
    for(int j = 1; j <= COLUNAS; j++){
      matrizA[i][j] = (double)rand()/RAND_MAX*10.0-1.0;
      printf("(%d,%d): %lf\n", i,j,matrizA[i][j]);
    }
    printf("-----------------\n");
  }

  return 0;

}
  • The indexation is of 0 a 7 in the case of LINES and of 0 a 9 in the case of COLUMNS, there’s your mistake. You’re indexing 1 a 8 and of 1 a 10. Do you understand or need an answer?

  • @Mauroalmeida, sorry, I may be wrong, but in the for I put that is less or equal, theoretically he would have to go through the 10 positions for columns and 8 for rows. Right?

  • The array is indexed to 0 and has 8 LINES, or has the right 0,1,2,3,4,5,6,7. If you try to access index 8, which does not exist, you are accessing a piece of memory that does not belong to you. How you put it <= and 8 equals 8 will do matrizA[8] and this is not allowed.

  • The problem is I just used the <=, do the math and you’ll see that theoretically and practically it goes from 1 to 8 and after 1 to 10, if you go through an array should go from 0 to 7 and 0 to 9.

  • 1

    It’s true! I removed it now and it worked, head is not good. Basic thing I’m traveling. Thanks!

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.