セグメンテーション障害(コアダンプ)C

Giorgos Mouch:

私は、malloc関数とX [N] [M]配列を作成しようとしている、と私は、このエラーが生じています。それと缶誰の助け私?

#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);
}

:私はすでに、この行を変更しようとしているsize = N*sizeof(int*);これに:size = N*sizeof(int);それでも同じエラーが表示されます。

アズハル:

コメントを参照してくださいする必要があり、コードの下、私はちょうどあなたのコードでは、非常に小さな変更を加えご覧ください。

#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);
}

おすすめ

転載: http://10.200.1.11:23101/article/api/json?id=377401&siteId=1