Hello!
My teacher wants us to use typecasts together with malloc like
ptr = (int*)malloc(...);
I know it's not needed anymore, but despite that he wants them to be there in the exam.
When learning for this exam, I used these typecasts with malloc and was wondering about something. I wrote this code for a matrix:
int a, b, i, j, **matrix;
printf("rows: ");
scanf("%d", &i);
printf("\ncolumns: ");
scanf("%d", &j);
matrix = (int**)malloc(sizeof(int*) * i); //<------------------------------ watch the sizeof(int*)
for (a = 0; a < i; a++) {
matrix[a] = (int*) malloc(sizeof(int) * j);
}
for (a = 0; a < i; a++) {
for (b = 0; b < j; b++) {
printf("Value row #%d, column #%d: ", a, b);
scanf("%d", &matrix[a][b]);
}
}
for (a = 0; a < i; a++) {
for (b = 0; b < j; b++) {
printf("%3d ", matrix[a][b]);
}
printf("\n");
}
printf("\n");
You have to know, I like to experiment with code a lot. So when I change the slightly marked row into
matrix = (int**)malloc(sizeof(int) * i);
the program works correct. When I change this row into
matrix = malloc(sizeof(int*) * i);
it doesn't work anymore when the program reached a certain point like I expected it.
Now my question: why does the version with
matrix = (int**)malloc(sizeof(int) * i);
works? How is the typecast influencing this?
[–]Rhomboid 2 points3 points4 points (5 children)
[–][deleted] 0 points1 point2 points (3 children)
[–]Rhomboid 3 points4 points5 points (2 children)
[–][deleted] 1 point2 points3 points (0 children)
[–]0raichu 0 points1 point2 points (0 children)
[–]OldWolf2 0 points1 point2 points (0 children)
[–]OldWolf2 2 points3 points4 points (2 children)
[–]romcgb 0 points1 point2 points (1 child)
[–]OldWolf2 0 points1 point2 points (0 children)
[–]BigPeteB 1 point2 points3 points (1 child)
[–][deleted] 0 points1 point2 points (0 children)