MPI_Datatype 的动态数组

Dynamic array of MPI_Datatype

以下是否有效:

int x; 
scanf("%d", &x);    //say 3

MPI_Datatype *sub ;
sub = calloc(x,sizeof(MPI_Datatype));

现在我们可以将 sub[0], sub[1], sub[2] 用作 MPI_Datatypes 吗?

是:

MPI_Datatype *sub = calloc(x, sizeof(MPI_Datatype));

MPI_Datatype sub[x] = { 0 };

在之后将 sub 用作数组时基本上是等效的。需要 { 0 } 初始化程序来匹配 calloc() 的内存归零属性。不同之处在于 &sub 在两种情况下都不相同:它在前一种情况下等于指针变量本身的地址,在后一种情况下等于数据的地址。所以总是使用&sub[0]来获取指向数组数据开头的指针。

如果您启用编译器的 C99 模式,例如使用 -std=c99,并且如果您希望 x 不是一个非常大的值,以便 MPI_Datatype 的数组适合堆栈,那么您可以简单地使用:

int x;
scanf("%d", &x);
MPI_Datatype sub[x];