您能解释一下为什么这段代码可以很好地工作吗?
#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>
typedef struct Point
{
double x;
double y;
} point;
int main(int argc, char *argv[]) {
int rank, size;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);
MPI_Datatype mpi_point;
MPI_Type_contiguous(2, MPI_DOUBLE, &mpi_point);
MPI_Type_commit(&mpi_point);
point local[2];
if(rank==0)
{
point *buf;
buf = malloc(10*sizeof(point));
for(int i = 0; i<10; i++)
{
buf[i].x= (double)i;
buf[i].y= (double)i+i;
}
MPI_Scatter(buf, 2, mpi_point, &local, 2, mpi_point, 0, MPI_COMM_WORLD);
free(buf);
}
else
{
point *buf = NULL;
MPI_Scatter(buf, 2, mpi_point, &local, 2, mpi_point, 0, MPI_COMM_WORLD);
}
printf("Hello, process %d has points: 1-> %f %f 2-> %f %f\n", rank, local[0].x, local[0].y, local[1].x, local[1].y);
MPI_Finalize();
return 0;
}
下面的这个不起作用?许多错误输出以segmentation fault
结尾。
#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>
typedef struct Point
{
double x;
double y;
} point;
int main(int argc, char *argv[]) {
int rank, size;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);
MPI_Datatype mpi_point;
MPI_Type_contiguous(2, MPI_DOUBLE, &mpi_point);
MPI_Type_commit(&mpi_point);
point *local;
if(rank==0)
{
point *buf;
buf = malloc(10*sizeof(point));
for(int i = 0; i<10; i++)
{
buf[i].x= (double)i;
buf[i].y= (double)i+i;
}
MPI_Scatter(buf, 2, mpi_point, &local, 2, mpi_point, 0, MPI_COMM_WORLD);
free(buf);
}
else
{
point *buf = NULL;
local = malloc(2*sizeof(point));
MPI_Scatter(buf, 2, mpi_point, &local, 2, mpi_point, 0, MPI_COMM_WORLD);
}
printf("Hello, process %d has points: 1-> %f %f 2-> %f %f\n", rank, local[0].x, local[0].y, local[1].x, local[1].y);
MPI_Finalize();
return 0;
}
唯一的区别是,local
在一种情况下被定义为向量“直接”,而在另一种情况下被定义为指针,然后我进行了malloc
处理。难道不是同一回事吗?两者都以相同的维度分配在堆栈中,那么带有malloc
的那个怎么可能不起作用?