Search code examples
cfor-loopmatrixscanfperfect-square

c function, that get a matrix, then squaring it


My target is a to write a c function, that reads a number n and the elements (type:double) of the n*n matrix, then i get back the result of multiplying the matrix by itself.

Example:

input:

3
1.0 0.0 0.0
1.0 1.0 1.0
0.0 0.0 1.0

output:

1.0 0.0 0.0
2.0 1.0 2.0
0.0 0.0 1.0

I have this:

#include <stdio.h>
#include <stdlib.h>

void square(){
    int n;
    scanf("%i", &n);
    double**matrix;
    matrix=(double**)malloc(n*sizeof(double*));
    int i;
    for(i=0; i<n; i++){
        matrix[i]=(double*)malloc(n*sizeof(double));
    }
    int j;
    for(i=0; i<n; i++){
        for(j=0; j<n; j++){
            scanf("%d", &matrix[i][j]);
        }
    }
    double**square;
    square=(double**)malloc(n*sizeof(double*));
    for(i=0; i<n; i++){
        square[i]=(double*)malloc(n*sizeof(double));
    }
    int k;
    for(i=0; i<n; i++){
        for(j=0; j<n; j++){
            square[i][j]=0;
            for(k=0; k<n; k++){
                square[i][j]+=matrix[i][k]*matrix[k][j];
            }
            printf("%d ", square[i][j]);
        }
        printf("\n");
    }
}

int main(){
    square();
    return 0;
}

My problem is that I can read only one row of the matrix, then i get back the square of something random n*n matrix. Maybe I'm using the variables in a bad way, I don't know.

I'm beginner and this is a homework.

Thank you for help! Sorry for bad English!


Solution

  • The %d format is used for scanning & printing ints, not doubles, and trying to use it to read doubles will result in garbage being stored in your matrix. Use %f instead.

    EDIT: Make that %lf for scanning and either %f or %lf for printing (the formats aren't symmetric).