2016-01-15 34 views
0

有史以來第一個問題,所以很抱歉,如果我錯過任何東西。 我試圖用C模擬物理中的二維靜電問題。 我有一個主陣列,我將在其上存儲每個點的電位和電荷密度值,然後是一個指向數組的存儲器地址的指針數組。需要爲2D元組數組和未知大小的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 */ 

回答

0

您將要使用malloc或calloc動態分配內存。我會在這裏假設A和B已經從用戶獲得:

tTuple * main_array; 

而在你的設置功能把

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

錯誤檢查,測試main_array不爲空。要得到一個元素,使用

main_array[i*b+j] 

我不知道你打算如何使用指針數組 - 它真的需要嗎? main_array具有元素內存位置。

+0

嘿ehaymore,謝謝你的回答。 是的,以後我需要指針數組,因爲我將代碼與MPI並行化。 我不太確定main_array [i * b + j]究竟是什麼意思? –

+0

你從calloc獲得的是一個可以用作一維數組的指針。既然你需要一個二維數組,你需要自己將矩陣索引轉換爲一維索引:行索引乘以coumns數加上列索引。然後在main_array中查看計算出的一維索引。 – ehaymore

+0

啊,我明白了。非常感謝您的幫助! –