gpt4 book ai didi

c - 初始化结构的矩阵(双指针)成员

转载 作者:太空宇宙 更新时间:2023-11-03 23:38:19 25 4
gpt4 key购买 nike

我在指点方面遇到了困难,有人可以帮我一下吗?

我正在尝试在结构数组中初始化一个双(双)指针,但不知何故我做错了。示例:

struct MyStruct
{
double **matrix;
};

double **CalculateMatrix(...)
{
double **matrix = (double**)malloc(ROWS * sizeof(double*));
for (int i = 0; i < ROWS; i++)
matrix[i] = (double*)malloc(COLS * sizeof(double));
// + assign some values
return matrix;
}

void Initialize(struct MyStruct *structs, int size)
{
for (int i = 0; i < size; i++)
// Here structs[i].matrix holds the correct matrix values
structs[i].matrix = CalculateMatrix(...);
}

int main()
{
struct MyStruct *structs = (struct MyStruct*)malloc(SIZE * sizeof(struct MyStruct));
Initialize(structs, SIZE);
// but once the function returns, matrix values are completely different
}

对不起,如果它是重复的,我找不到任何东西

最佳答案

这里不需要全局变量。因此,您可以在 main 方法中声明、定义和初始化结构数组的大小,以及矩阵的维度。

此外,您的方法名称具有误导性,我将它们更改为可以向作者传达每个函数的用途的名称。或者,更准确地说,您的方法执行的任务不止一项。为可重用性划分任务是很好的做法。

这是一个让您入门的最小示例:

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

struct MyStruct
{
double **matrix;
};

double **allocate_matrix(int rows, int cols)
{
double **matrix = malloc(rows * sizeof(double*));
for (int i = 0; i < rows; i++)
matrix[i] = malloc(cols * sizeof(double));
return matrix;
}

void allocate_matrices(struct MyStruct *structs, int size, int rows, int cols)
{
for (int i = 0; i < size; i++)
structs[i].matrix = allocate_matrix(rows, cols);
}

void fill_matrices(struct MyStruct *structs, int size, int rows, int cols)
{
for (int i = 0; i < size; i++)
for(int j = 0; j < rows; j++)
for(int z = 0; z < cols; z++)
structs[i].matrix[j][z] = -1.2;
}

void print_matrices(struct MyStruct *structs, int size, int rows, int cols)
{
for (int i = 0; i < size; i++)
for(int j = 0; j < rows; j++)
for(int z = 0; z < cols; z++)
printf("%f\n", structs[i].matrix[j][z]);
}

void free_matrices(struct MyStruct *structs, int size, int rows) {
for (int i = 0; i < size; i++) {
for(int j = 0; j < rows; j++) {
free(structs[i].matrix[j]);
}
free(structs[i].matrix);
}
}


int main()
{
int rows = 3, cols = 4, size = 2;
struct MyStruct *structs = malloc(size * sizeof(struct MyStruct));
structs[0].matrix = NULL;
structs[1].matrix = NULL;
if(structs[0].matrix == NULL)
printf("null\n");
allocate_matrices(structs, size, rows, cols);
if(structs[0].matrix == NULL)
printf("null\n");
fill_matrices(structs, size, rows, cols);
print_matrices(structs, size, rows, cols);
free_matrices(structs, size, rows);
free(structs);
}

输出:

null
-1.200000
-1.200000
-1.200000
-1.200000
-1.200000
-1.200000
-1.200000
-1.200000
-1.200000
-1.200000
-1.200000
-1.200000
-1.200000
-1.200000
-1.200000
-1.200000
-1.200000
-1.200000
-1.200000
-1.200000
-1.200000
-1.200000
-1.200000
-1.200000

灵感来 self 的 2D dynamic array (C) .

关于c - 初始化结构的矩阵(双指针)成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53408525/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com