【发布时间】:2019-01-14 13:32:33
【问题描述】:
我的程序正在编译并显示异常行为。
使用以下命令进行编译
mpicc one.c -o one
mpiexec -n 2 ./one
我尝试调试它,但没有显示编译错误。 我不明白为什么我的程序行为异常
#include<mpi.h>
#include<stdio.h>
#include<string.h>
int main(int argc,char * argv[])
{
char str[434];
int n;
int rank,size; MPI_Status status;
MPI_Init(&argc,&argv);
MPI_Comm_rank(MPI_COMM_WORLD,&rank);
MPI_Comm_size(MPI_COMM_WORLD,&size);
if(rank == 0)
{//Sender process
scanf("%s",&str);
MPI_Ssend(&n,1,MPI_INT,1,0,MPI_COMM_WORLD);
MPI_Ssend(&str,n,MPI_CHAR,1,0,MPI_COMM_WORLD);
printf("Sending word %s in process 0\n",str);
}
else
{//Receiver process
MPI_Recv(&n,1,MPI_INT,0,0,MPI_COMM_WORLD,&status);
MPI_Recv(&str,n,MPI_CHAR,0,0,MPI_COMM_WORLD,&status);
printf("Receiving word %s in process 1\n",str);
}
MPI_Finalize();
return 0;
}
输入:
哈哈
实际结果
在进程0中发送单词哈哈
在过程1中接收单词haha
交换结果
在进程0中发送单词哈哈
在进程1中接收字��������
【问题讨论】:
-
启用编译器警告。您正在传递一个指向数组的指针地址,例如
scanf你应该简单地将指针传递给数组str。稍后在您的代码中也会出现同样的问题。 -
你永远不会初始化
n。而且您不应该使用&str,它是指向数组的指针(类型为char (*)[434])。使用&str[0]或普通str(衰减为&str[0])。&str的这种用法在你使用它的任何地方都是错误的。