c - Segmentation fault, 2-Dimensional Matrix, malloc -
i'm trying create 2-dimensional array using malloc. code seems correct when try set values, receive "segmentation fault" message.
#include <stdio.h> #include <stdlib.h> int main(){ int i, j; int **m = (int **) malloc(5 * sizeof(int)); if(m == null){ printf("error"); getchar(); exit(-1); } for(i = 0; < 5; i++){ m[i] = (int *) malloc(5 * sizeof(int)); if(m[i] == null){ printf("error"); getchar(); exit(-1); } } for(i = 0; < 5; i++){ for(j = 0; j < 5; j++){ printf("%d %d\n", i, j); m[i][j] = 0; } } for(i = 0; < 5; i++){ for(j = 0; j < 5; j++){ printf("%d ", m[i][j]); } printf("\n"); } }
thanks.
change
int **m = (int **) malloc(5 * sizeof(int));
to
//---------------------------------------v int **m = (int **) malloc(5 * sizeof(int *));
your code fail size of int
not equal size of pointer variable.
Comments
Post a Comment