问题
I have the following structures.
typedef struct arr_integer
{
int size;
int *arr;
}arr_arr_integer;
arr_arr_integer alloc_arr_integer(int len)
{
arr_arr_integer a = {len, len > 0 ? malloc(sizeof(int) * len) : NULL};
return a;
}
What I intend to do is fill the matrix with the above structures. But I don't know how to manipulate the structure to fill the matrix.
Tried it this way, but I get an error.
int main(int argc, char const *argv[])
{
int len,rows,columns;
scanf("%d",&rows);
scanf("%d",&columns);
len = rows * columns;
arr_arr_integer Matrix = alloc_arr_integer(len);
for (int i = 0; i < rows ; i++)
{
for (int j = 0; j < columns; j++)
{
scanf("%d",&Matrix.arr[i].arr[j]);
}
}
return 0;
}
回答1:
Since you have a 2D matrix, it's much better/easier to store both dimensions in the matrix struct
instead of the total (e.g. len
).
And, it helps to have a function that returns a pointer to a given cell.
Here's a refactored version of your code.
I've generated two print functions that show a simple version and a somewhat faster version.
#include <stdio.h>
#include <stdlib.h>
typedef struct arr_integer {
int ymax;
int xmax;
int *arr;
} arr_arr_integer;
arr_arr_integer
alloc_arr_integer(int ymax,int xmax)
{
arr_arr_integer a;
a.ymax = ymax;
a.xmax = xmax;
a.arr = malloc(ymax * xmax * sizeof(int));
return a;
}
int *
mtxloc(arr_arr_integer *mtx,int y,int x)
{
return &mtx->arr[(y * mtx->xmax) + x];
}
void
mtxprt(arr_arr_integer *mtx)
{
for (int i = 0; i < mtx->ymax; i++) {
for (int j = 0; j < mtx->xmax; j++) {
int *ptr = mtxloc(mtx,i,j);
printf(" [%d,%d]=%d",i,j,*ptr);
}
printf("\n");
}
}
void
mtxprt2(arr_arr_integer *mtx)
{
for (int i = 0; i < mtx->ymax; i++) {
int *ptr = mtxloc(mtx,i,0);
for (int j = 0; j < mtx->xmax; j++)
printf(" [%d,%d]=%d",i,j,ptr[j]);
printf("\n");
}
}
int
main(int argc, char **argv)
{
int len, rows, columns;
scanf("%d", &rows);
scanf("%d", &columns);
arr_arr_integer Matrix = alloc_arr_integer(rows,columns);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
int *ptr = mtxloc(&Matrix,i,j);
scanf("%d", ptr);
}
}
mtxprt(&Matrix);
mtxprt2(&Matrix);
return 0;
}
来源:https://stackoverflow.com/questions/63767458/fill-an-matrix-with-the-following-structure-in-c