Segmentation fault(core dumped) C

Giorgos Mouch :

I am trying to make an X[N][M] array with malloc, and I am having this error. Can anybody help me with that ?

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

int main(int argc, char argv[])
{
  int N,M;  // N=megethos rows , M=megethos columns
  int **X;  // pinakas
  int size,i,j;


  printf("Give me the rows of the table: ");
  scanf("%d",&N);
  printf("Give me the columns: ");
  scanf("%d",&M);

  size = N*sizeof(int*);
  X = malloc(size);

  size = M * sizeof(int*);
  for(i=0; i<N;i++){
    X =malloc(size);
  }

  for(i=0;i<N;i++){
    for(j=0;j<M;j++){
      printf("Eisagwgh toy %d - %d stoixeioy: ",i+1,j+1);
      scanf("%d",&X[i][j]);
    }
  }

  for(i=0;i<N;i++){
    printf("\n");
    for(j=0;j<M;j++){
      printf("%d",X[i][j]);
    }
  }
  free(X);
}

I have already try to change this line: size = N*sizeof(int*); to this: size = N*sizeof(int); but still same error appear.

Azhar :

Please see the below code, I just made a very small change in your code, must see the comment.

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char argv[])
{
  int N,M;  // N=megethos rows , M=megethos columns
  int **X;  // pinakas
  int size,i,j;


  printf("Give me the rows of the table: ");
  scanf("%d",&N);
  printf("Give me the columns: ");
  scanf("%d",&M);

  size = N*sizeof(int*);
  X = malloc(size);

  size = M * sizeof(int*);
  for(i=0; i<N;i++){
      //Here it intialize each row with size
    X[i] =malloc(size);
  }

  for(i=0;i<N;i++){
    for(j=0;j<M;j++){
      printf("Eisagwgh toy %d - %d stoixeioy: ",i+1,j+1);
      scanf("%d",&X[i][j]);
    }
  }

  for(i=0;i<N;i++){
    printf("\n");
    for(j=0;j<M;j++){
      printf("%d",X[i][j]);
    }
  }
  free(X);
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=376091&siteId=1