【问题标题】:Need to allocate memory for both a 2D tuple array and a 2D pointer array of unknown size?需要为 2D 元组数组和未知大小的 2D 指针数组分配内存?
【发布时间】:2016-04-21 04:03:37
【问题描述】:

第一次在这里提问,如果我错过了什么,很抱歉。 我正在尝试用 C 对物理学中的 2D 静电问题进行建模。 我有一个主数组,我将在其中存储每个点的电势和电荷密度值,然后是一个指针数组,它将内存地址提供给主数组。

但是我不知道编译时的数组大小,因为它是运行时的用户输入,因此需要能够动态分配内存。 这是我已经拥有的,任何帮助表示赞赏。谢谢!

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

typedef struct tTuple { //Create new type called tuple
    double poten; //potential
    double cden; //charge density
} tuple;



int i, j;
int N, M;
#define a 10 //Grid Width
#define b 10 //Grid Height
int x1, y1, x2, y2; //Positions of two point charges
int my_rank, comm_size;
double w;

tuple  mainarray [a][b];
double *pointerarray[a][b];
int convflag = 1;  //Global convergence checker flag


/* More code below with main function containing scanf etc */

【问题讨论】:

    标签: c arrays dynamic malloc 2d


    【解决方案1】:

    您需要使用 malloc 或 calloc 来动态分配内存。我在这里假设 a 和 b 已经从用户那里获得:

    tTuple * main_array;
    

    然后在你的设置函数中放

    main_array = calloc(a*b, sizeof(tTuple));
    

    对于错误检查,测试 main_array 不为 NULL。要获取元素,请使用

    main_array[i*b+j]
    

    我不确定您打算如何使用指针数组 - 真的需要吗? main_array 具有元素内存位置。

    【讨论】:

    • 嘿 ehaymore,谢谢你的回答。是的,我稍后将需要指针数组,因为我正在使用 MPI 并行化代码。我不太确定 main_array[i*b+j] 到底是什么意思?
    • 你从 calloc 得到的是一个可以用作一维数组的指针。由于您需要一个二维数组,因此您需要自己将矩阵索引转换为一维索引:行索引乘以列数加上列索引。然后在 main_array 中查看计算得到的一维索引。
    • 啊,我明白了。非常感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-02
    • 2015-12-10
    • 1970-01-01
    相关资源
    最近更新 更多