![](/img/trans.png)
[英]Using MPI_Type_create_struct() to transfer structs containing dynamic arrays in C
[英]opaque c struct containing dynamic arrays
這是為包含動態數組的結構分配內存的正確方法嗎? 特別是,考慮到尚不知道結構的實際大小,我為myStruct分配內存的方式是否正確?
//test.h
struct Test;
struct Test * testCreate();
void testDestroy(struct Test *);
void testSet(struct Test *, int);
//test.c
#include <stdlib.h>
struct Test{
double *var;
};
struct Test * testCreate(int size){
struct Test *myTest = (struct Test *) malloc(sizeof(struct Test));
myTest->var = malloc(sizeof(double)*size);
return(myTest);
}
void testDestroy(struct Test * myTest){
free(myTest->var);
free(myTest);
}
void testSet(struct Test * myTest, int size){
int i;
for (i=0;i<size;++i){
myTest->var[i] = i;
}
}
struct
具有固定的大小,這就是sizeof
返回的內容。
您的結構具有on元素,雙指針,並且具有(與平台有關的)固定大小。
您的testCreate
函數可以正確執行操作。 如果您不知道動態分配的部分的大小,可以將指針設置為NULL
以表示必須稍后分配內存。
是的,您正確地為該結構分配了空間,然后為該結構中的雙精度數組分配了空間。 實際上,在嘗試使用內存之前,應始終測試malloc()的返回是否為NULL。 同樣,大多數類似這樣的程序也將數組的大小存儲在結構中,因此您可以編寫更通用的代碼以確保它不會在分配的空間的末尾運行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.