c - 如何用C语言创建矩阵结构?

标签 c pointers matrix struct

我是 C 初学者,但我目前正在尝试创建一个可以在不同函数中使用的矩阵数据结构,而无需显式传递列数和行数(例如:matrixMult (矩阵 A, 矩阵 B) 而不是 matrixMult(A, B, rowsA, columnsA, rowsB, columnsB) )。到目前为止,我的方法是声明一个结构,例如

typedef struct matrix{
    int rows;
    int columns;
    int **data;
}matrix;

然后,为了正确分配矩阵,我尝试使用以下函数

matrix startmatrix(matrix mat,int n_row, int n_col){
    int i=0;
    mat.rows=n_row;
    mat.columns=n_col;

    mat.data=(int **) calloc(n_row,sizeof(int *));

    for(i=0;i<n_row;i++){
        mat.data[i]=(int *) calloc(n_col,sizeof(int));
    }
    return mat;
}

(据我理解)它分配包含列的行,然后为列分配内存,然后列包含实际数据。

代码的上述部分似乎工作正常,但是当我尝试将一些数据输入到矩阵然后稍后将其可视化时,例如:

A=startmatrix(A,2,3);
A.data[1,1]=1;
printf("%d",A.data[1,1]);

它返回一个警告(赋值使指针来自整数而不进行强制转换)和实际矩阵内的数字 4。

谁能解释一下我做错了什么吗?


编辑:添加我正在使用的完整代码。到目前为止,它只包含 2 个文件:mainfile.c 和matrix.h。我现在也明白(谢谢!)将 mat 传递给 startmatrix 是没有用的,我应该使用 A.data[][],所以我相应地编辑了代码。 到目前为止,主要文件是:

//Mainfile.c
#include <stdio.h>
#include <stdlib.h>
#include "matrix.h"


int main(){
    matrix A=startmatrix(2,3); //2 by 3 matrix
    A.data[1][1]=1; /*testing to see if the value 1 is passed to the first cell*/

    printf("\n%d\n",A.rows); //Prints number of rows stored by A
    printf("\n%d\n",A.columns); //Prints number of cols stored by A
    printf("\n%d\n\n",A.data[1][1]);  //Is supposed to print the value stored in the first cell
    return 0;
}

这会调用文件“matrix.h”,其中包含以下内容(到目前为止仅包含以下内容)

#include <stdlib.h>

typedef struct matrix{
    int rows, columns;
    int **data;
}matrix;

matrix startmatrix(int n_row, int n_col){
    matrix mat;
    int i=0;
    mat.rows=n_row;
    mat.columns=n_col;

    mat.data=(int **) calloc(n_row,sizeof(int *));

    for(i=0;i<n_row;i++){
        mat.data[i]=(int *) calloc(n_col,sizeof(int));
    }
    return mat;
}

到目前为止,这就是我用于解决此问题的所有代码,仅此而已。我正在阅读建议的答案和评论并尝试它们,看看它们是否有效。提前感谢您的帮助。

最佳答案

你不能像那样访问二维数组 - C 不会这样对待它,对于编译器来说,它只是一个指向整数的指针。 C 也不识别多重索引的表示法(用逗号分隔的多个索引)。

您应该使用 A.data[1] 访问该行,它为您提供指向特定行的指针,然后访问其中所需的项目 - A.data[1 ][1].

关于c - 如何用C语言创建矩阵结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51124448/

相关文章:

c - 传递到内核的值变得困惑

c - 错误: expected specifier-qualifier-list before

c - 如何递归地相乘并打印2个数字的数字

c - 寻找最接近的质数

特定类型的指针可以分配给指向包含与其成员之一相同类型的 union 体的指针吗?

c - 将字符串存储在另一个字符串的指针数组中

r - 使用 for 循环进行矩阵计算

c - C中指向指针和realloc的指针

javascript - 将 SVG 重置为原始变换矩阵

c - 读取文件以在 c 中创建矩阵