Ognjen Ognjen - 3 months ago 13
C Question

Fill matrix using pointers

The main idea of code below is to make new type which is actually integer matrix. After that make functions for reading and writing to std output. Mentioned functions have to be with pointers in arguments. Something is wrong, these functions wont work.

#include <iostream>
#include<stdio.h>
#include<conio.h>

typedef int SQM[3][3];

SQM *m;


void scan(SQM *sqm){

int size = 3;
int column,row = 0;

printf("\nEnter matrix : ");

for (row = 0; row < size; row++) {
for (column = 0; column < size; column++)
scanf("%d", &sqm[row][column]);
}
}
void print(SQM *sqm){

int size = 3;
int row, column = 0;

printf("Entered matrix is : \n");

for (row = 0; row < size; row++) {
printf("\n");
for (column = 0; column < size; column++) {
printf("\t%d", sqm[row][column]);
}
}
}
int main() {

scan(m);
print(m);

return 0;
}

Answer

Don't mix C and C++

#include <iostream> /* Delete this line */
#include <stdio.h>

And you need to reserve space for m before using it.

Try:

int main(void)
{ 
    m = malloc(sizeof *m);
    if (m != NULL) {
        scan(m);
        print(m);
    }
    return 0;
}

Notice that you can avoid the global passing an address:

int main(void)
{ 
    SQM m;

    scan(&m);
    print(&m);
    return 0;
}

Finally, (as a question of style) don't use magic numbers like 3:

#define SQM_SIZE 3

typedef int SQM[SQM_SIZE][SQM_SIZE];

...

for (row = 0; row < SQM_SIZE; row++) {
    for (column = 0; column < SQM_SIZE; column++)