1

i'm new to c. i'm writing a .h file dedicated to matrix. I want to write a function in .h file that returns a matrix (array) (not possible in c), so the real return is a pointer to a local array variable. But i can't use a local pointer in the main funct, so i've changed the int matrix[][] to static int matrix[][]. The problem now is: the user insert the number N of rows/columns, but a static array can only take a constant dimension. help

This is the .h

int N;
int i;
int j;

int *get_matrix(){
  int user_input;

  printf("set the dimension NxN of your matrix >> N=");
  scanf("%d",&N );

  static int temp_matrix[N][N];
  for(i=0;i<N;i++){
    for(j=0;j<N;j++){
      printf("insert the matrix[%d][%d] value\n",i,j );
      scanf("%d",&user_input);
      temp_matrix[i][j]=user_input;
    }
  }

  return temp_matrix;
}


void print_matrix(int *matrix){
  for(i=0;i<sizeof(matrix)/4;i++){
    for(j=0;j<sizeof(matrix)/4;j++){
      printf("%7d",matrix[i][j]);
  printf("\n");
    }
  }
}

this is the main.c file

#include <stdio.h>
#include "matrix_math.h"

void main(void){
  int i;
  int j;


  int *p1 = get_matrix();
  int matrix1[N][N];
  for(i=0;i<N;i++){
    for(j=0;j<N;j++){
      matrix1[i][j]=p[i][j];
    }
  }

  print_matrix(matrix1);
}
Jokey
  • 71
  • 6

1 Answers1

0

If this is just a school homework, and malloc not allowed/needed, and assuming it is acceptable to limit code to some reasonable upper limit N, consider defining matrix as a struct

#define MAXN 20

struct matrix {
     int n ;
     int data[MAXN][MAXN] ;
}


// matrix.c
struct matrix get_matrix() { ... ; return m } ;

void print_matrix(struct m *mp) {
  for (int i = 0 ; i<mp->n ; i++) {
     ...
  } ;
} ;

And then you can pass "matrix" around. Needless to say, better to pass matrix * whenever possible to improve performance. You can also make functions that return matrix, if needed.

dash-o
  • 13,723
  • 1
  • 10
  • 37
  • ok i'll try. i have no knowledge about struct and "malloc" , i can start looking at some guide online. Wich one should i start? At university we have seen Array and puntator (and variable, scopes, basics of c etc.), and with this program i'm tryng to do something i can't do yet maybe? – Jokey Nov 10 '19 at 12:45
  • It's up to you to decide which one to use. In real applications you will make extensive use of BOTH, and they are both considered essential, and the concepts apply to all modern programming languages. I would start with struct, and they are simpler, `malloc` is usually used with struct. – dash-o Nov 10 '19 at 13:33