在 c 中使用以下结构填充矩阵 [英] Fill an matrix with the following structure in c
本文介绍了在 c 中使用以下结构填充矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下结构.
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;
}
推荐答案
由于您有一个 2D 矩阵,因此在矩阵 struct
两个维度会更好/更容易> 而不是总数(例如 len
).
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;
}
这篇关于在 c 中使用以下结构填充矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文