Alright, I'm having trouble understanding how to use malloc in calloc to initalize an array. I'm trying to do some practice by creating a 2 * 3 matrix that stores user-input values. The only part of the code that I don't want to change is using **matrix instead of matrix[5][7]. Any suggestions?
Here's my code so far (I keep getting segmentation faults):
#include<stdio.h>
#include<stdlib.h>
main(){
int i, j;
int **mat = (int **)malloc(2 * 3 * sizeof(int*));
for(i=0;i<2;i++)
for(j=0;j<3;j++){
printf("Input a value for Array[%d][%d]: ",i,j);
scanf("%d",&mat[i][j]);
}
for(i=0;i<2;i++)
for(j=0;j<3;j++)
printf("%d\t",mat[i][j]);
}
EDIT: I appreciate the help everyone! My code now works without faults. Here's the what it looks like:
#include<stdio.h>
#include<stdlib.h>
main(){
int i, j;
int **mat;
mat = malloc(2 *sizeof(int *));
for(i=0;i<2;i++){
mat[i] = malloc(3 *sizeof(int));
for(j=0;j<3;j++){
printf("Input a value for Array[%d][%d]: ",i,j);
scanf("%d",&mat[i][j]);
}
}
for(i=0;i<2;i++)
for(j=0;j<3;j++)
printf("%d\t",mat[i][j]);
return 0;
}
If there's any reason I should make more edits, let me know.