gpt4 book ai didi

c - 如何使用动态内存分配处理 C 中的矩阵?

转载 作者:太空宇宙 更新时间:2023-11-04 02:35:11 24 4
gpt4 key购买 nike

我试图运行一个模拟,其中我需要填充三个大小为“2 x 迭代”的矩阵,这是 (iterations=)10^8 列和 2 行。我还使用大小为 10^8 的 vector t。使用动态内存分配,我编写了以下代码:

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

#define T 10000
#define dt 0.0001
#define iterations (T/dt)

/*(more code)*/
int main(){
int i, j;
double *t;
double (*x)[2], (*y)[2], (*c)[2];

t=(double *) malloc((iterations-1)*sizeof(double));
x=(double (*)[2]) malloc((2*(iterations))*sizeof(double));
y=(double (*)[2]) malloc((2*(iterations))*sizeof(double));
c=(double (*)[2]) malloc((2*(iterations))*sizeof(double));

for(i=0; i=1; i++){
x[i][0]=50+500*i;
y[i][0]=300;
c[i][0]=15;
}

for(j=0; j<=iterations-2; j++){
t[j+1]=t[j]+dt;
/*(more code)*/
printf("%G %G %G %G %G %G\n",x[0][j+1],x[1][j+1],y[0][j+1],y[1][j+1],c[0][j+1],c[1][j+1]);
}
return 0;
}

动态内存分配是否写对了?我的意思是,我真的有一个大小为“迭代”的 vector t 和三个大小为“2 x 迭代”的矩阵吗?

而且,如果我想填充矩阵的每个分量,例如我想在矩阵 x 的位置 (1,4) 处有一个 50,那么我是否必须写 x[1][4]=50 ? (就像第一个“for”一样。)

问题是执行程序时出现错误:段错误。然后,使用调试器我得到以下信息:

程序接收到信号 SIGSEGV,段错误。

x[0][0]=50

最佳答案

分配矩阵的通用方法:

double **mat_init(int n_rows, int n_cols)
{
double **m;
int i;
m = (double**)malloc(n_rows * sizeof(double*));
for (i = 0; i < n_rows; ++i)
m[i] = (double*)calloc(n_cols, sizeof(double));
return m;
}
void mat_destroy(int n_rows, double **m)
{
int i;
for (i = 0; i < n_rows; ++i) free(m[i]);
free(m);
}

你也可以这样做:

double **mat_init2(int n_rows, int n_cols)
{
double **m;
int i;
m = (double**)malloc(n_rows * sizeof(double*));
m[0] = (double*)calloc(n_rows * n_cols, sizeof(double));
for (i = 1; i < n_rows; ++i)
m[i] = m[i-1] + n_cols;
return m;
}
void mat_destroy2(double **m)
{
free(m[0]); free(m);
}

对于上述两种方法,您都可以使用matrix[row][col] 来访问单元格。有时,您可能更喜欢分配单个数组并使用 matrix[row*n_cols+col] 访问单元格。

顺便说一句,我相信有人会说“不要使用 cast”,但使用 cast 有好处——这是题外话。

关于c - 如何使用动态内存分配处理 C 中的矩阵?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38565755/

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