Home > Blockchain >  A function that prints a matrix row
A function that prints a matrix row

Time:05-06

I'm trying to write a function that prints a matrix row chosen by user. It works for the first row of the matrix but it doesn't work for other rows. Here's my code.

row: the row we want to print n: number of the rows/columns in matrix

Matrix (nxn)

Code:

#include <stdio.h>
#define SIZE 50

void prow(float *arr, int row, int n){  
    int i;
    for(i = row * n; i < (row * n)   n; i  ){
        printf("%f ", *(arr i));
    }

}

int main(){
    int n, i, j;
    float matrix[SIZE][SIZE];

    printf("Row / column number: ");
    scanf("%d", &n);

    for(i = 0; i < n; i  ){
        for(j = 0; j < n; j  ){
            printf("[%d][%d] element: ", i, j);
            scanf("%f", &matrix[i][j]);
        }
    }


    prow(&matrix[0][0], 2, n);

    return 0;
}

CodePudding user response:

The compiler already knows your array is 50 x 50 and nothing else

#define SIZE 50
float matrix[SIZE][SIZE];

but you are (probably?) using the array as if it had a different size, because you input n as size. So when you assign the entries,

scanf("%f", &matrix[i][j]);

they aren't being put in the right places (each row is still 50 entries according to the compiler, despite n being something else).

Make sure n and SIZE match.

  • Related