2

I have a very basic question regarding arrays in C. i have this struct:

struct Matrix{   
int rows;
int cols;
int** matrix;
};

and when i tried to use this struct and to declare a Matrix, i have come across this problem

Matrix matrix;           
matrix->matrix = (int**) malloc(3*sizeof(int*));//allocates pointer to a pointers array

for (int i = 0; i <3; i++){

    matrix->matrix[i] = (int*) malloc(3*sizeof(int));
}//allocating a 3X3 array

matrix->matrix={1,2,3,4,5,6,7,8,9};

however that last line won't work, apparently because the compiler doesn't understand the size of my array.

even when I try to do it this way:

matrix->matrix={{1,2,3},{4,5,6},{7,8,9}};

does anyone know how to do this ? it seems to me like something very simple. thanks a lot!

Steven V
  • 16,357
  • 3
  • 63
  • 76

2 Answers2

2

The kind of initialization that you are attempting to apply is valid only upon declaration.

For example:

int array[9]    = {1,2,3,4,5,6,7,8,9};
int table[3][3] = {{1,2,3},{4,5,6},{7,8,9}};

You can initialize the matrix as follows:

for (int i=0; i<3; i++)
    for (int j=0; j<3; j++)
        matrix->matrix[i][j] = i*3+j+1;
barak manos
  • 29,648
  • 10
  • 62
  • 114
0
#include <stdio.h>
#include <stdlib.h>

typedef struct Matrix{
    int rows;
    int cols;
    int** matrix;
} Matrix;

Matrix *Create_Matrix(int rows, int cols, const int *values){
    Matrix *matrix;

    matrix = malloc(sizeof(Matrix));
    matrix->rows = rows;
    matrix->cols = cols;
    matrix->matrix = malloc(rows * sizeof(int*));
    for(int i=0; i < rows ;++i){
        matrix->matrix[i] = malloc(cols * sizeof(int));
        for(int j=0;j < cols; ++j)
            matrix->matrix[i][j] = *values++;
    }

    return matrix;
}

int main(){
    Matrix *m = Create_Matrix(3, 3, (int[]){1,2,3,4,5,6,7,8,9});
    for(int r=0;r<3;++r){
        for(int c=0;c<3;++c)
            printf("%d ", m->matrix[r][c]);
        printf("\n");
    }
    return 0;
}
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70