c - 结构内部的动态矩阵,C 编程

标签 c matrix dynamic struct

我需要帮助。我想学习如何创建和使用作为结构元素的动态矩阵,我想用零 (0) 填充矩阵并将其打印出来,我尝试了很多方法但没有运气。这是代码

#include <stdio.h>
#include <stdlib.h>

typedef struct matrica
{
    int **mat;
    int dim; //this is dimension of squared matrix

}MATRICA;

void form_matrix(MATRICA *matrica);

int main()
{

    MATRICA matrix;

    form_matrix(&matrix);


    return 0;
}

void form_matrix(MATRICA *matrica)
{
    int i, j;
    MATRICA *br;

    do
    {
        printf("Size of matrix ");
        scanf("%d", &br->dim);

    }while(br->dim < 4 || br->dim > 6);

    matrica->mat = (int **) calloc(br->dim, sizeof(int *));

    for(i = 0; i < br->dim; i++)
    {
        matrica->mat[i] = (int *) calloc(br->dim, sizeof(int));

        for(j = 0; j < br->dim; j++)
        {
            matrica->mat[i][j] = 0;
        }
    }

    for(i = 0; i < br->dim; i++)
        for(j = 0; j < br->dim; j++)
            printf("%d ", matrica->mat[i][j]);

}

我做错了什么,我的函数内部循环只执行一次,有人可以向我解释为什么吗?

最佳答案

您的程序表现出未定义的行为,因为您正在取消引用未初始化的指针br。您不需要它,您只需要一个变量来存储您的维度输入。

int i, j, dim;

do
{
    printf("Size of matrix ");
    if (scanf("%d", &dim) != 1) {
        printf("scan failed\n");
        exit(EXIT_FAILURE);
    }

}while(dim < 4 || dim > 6);

matrica->dim = dim;
/* ... replace all instances of br->dim with dim */

关于c - 结构内部的动态矩阵,C 编程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38595720/

相关文章:

C - 十六进制值 0x00 未写入文件

matlab - 使用 MatLab 将逻辑转换为矩阵

python - 如何与向量一起遍历矩阵?

CSS 问题,100% 宽度一直在错位

dynamic - 在运行时向窗体上的每个控件添加事件处理程序 VB6

c - 数组索引大于声明值。这怎么可能?

c - getopt() : Is optarg guaranteed to be non-NULL if optstring contains something like "a:"?

用于检查整数溢出的编译器标志

r - 将矩阵拆分为 R 中的多对列

java - 更改for循环的顺序?