Reputation: 53
I've tried to create a matrix in C and have some input value, but I don't know why it throws me a "segmentation error". This is my code:
#include <stdio.h>
#include <stdlib.h>
int main() {
int i;
int j;
int **a;
a = malloc(5 * sizeof(int));
for (i = 0; i < 5; i++) {
a[i] = malloc(4 * sizeof(int));
}
for (i = 0; i < 5; i++) {
for (j = 0; j < 4; j++) {
scanf("%d", (a[i][j]));
}
}
return 0;
}
Upvotes: 1
Views: 1786
Reputation: 213276
Given the answer by @Bathsheba, this is what your code should look like:
#include <stdio.h>
#include <stdlib.h>
int main (void)
{
int (*a)[4] = malloc( sizeof(int[5][4]) );
for(int i=0;i<5;i++)
{
for(int j=0;j<4;j++)
{
scanf("%d", &a[i][j]);
}
}
free(a);
return 0;
}
Upvotes: 2
Reputation: 234635
a
should bea=malloc(5*sizeof(int*));
Note well the pointer type in the sizof
. On some systems (Windows desktops in the early 2000s) an int
just happened to be the same size as an int*
, but you must not assume that.
scanf
takes a pointer as the parameter: the clearest way to write this is scanf("%d", &a[i][j]);
Don't forget to free
the memory once you're all done.
Finally, I die a little inside every time I see a matrix modelled like this. Granted, it allows you to use the [][]
notation, but normally it's better to model it as a contiguous memory block and use the idiom i * columns + j
to access the element at (i, j)
.
Upvotes: 0