I am studying pointers in C/C++ and as my little project to learn this problematic I am trying to develop a simple application doing operations with matrixies. I want to ask if this way I am using pointers and dynamic allocation in is correct or I am making it wrong. Thanks 🙂
#include <stdlib.h>
#include <stdio.h>
int numberRows;
int numberCollumns;
void getSize()
{
printf("Write down size of matrix in format Rows Collumns: ");
scanf("%i %i", &numberRows, &numberCollumns);
}
void getMatrix(int *m[])
{
int x = 0;
int y = 0;
while(x<numberRows)
{
while(y<numberCollumns)
{
scanf("%i", &m[x][y]);
y++;
}
x++;
y = 0;
}
}
void writeMatrix(int *m[])
{
int x = 0;
int y = 0;
while(x<numberRows)
{
while(y<numberCollumns)
{
printf("%i ", m[x][y]);
y++;
}
printf("\n");
x++;
y = 0;
}
}
int main()
{
getSize();
int **matrix;
matrix = (int**)malloc(numberRows*sizeof(int*));
int x = 0;
while(x < numberCollumns)
{
matrix[x] = (int*)malloc(numberCollumns*sizeof(int));
x++;
}
getMatrix(matrix);
printf("\n\nMatrix: \n");
writeMatrix(matrix);
return 0;
}
I found a problem:
Your loop condition is wrong. What if the number of rows and columns do not match up?
Also, I do not seeing any corresponding calls to
free.As for code style, your while loops would look better as for loops:
Side Note
The code is pure C (well except for the casting of the return from
malloc). C++ code would look a lot different.