我正在尝试编写一个 c 程序,它从用户那里获取两个 float ,然后使用 execv() 命令调用另一个程序。但我做不到,因为将 float 转换为 char 或者我不知道为什么。 问题是 execv() 命令不起作用;输出必须是这样的
Enter first num: 5
Enter second num: 7
5.000000 + 7.000000 = 12.000000
parentPID: 9745 childPID: 9746 works now
但是现在是这样
Enter first num: 5
Enter second num: 7
parentPID: 9753 childPID: 9754 works now
我的第一个c程序sum.c
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main(int argc, char **argv) {
if(argc!=3)
printf("error...\n");
double a=atof(argv[1]);
double b=atof(argv[2]);
printf("%lf + %lf = %lf \n",a,b,a+b);
return 0;
}
和第二个程序calculate.c
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main()
{
float x,y;
pid_t pid;
printf("Enter first num: ");
scanf("%f",&x);
printf("Enter second num: ");
scanf("%f",&y);
if((pid=fork())== -1)
{
printf("can not fork..\n");
exit(1);
}
if(pid==0) //child
{
pid=getpid();
char *temp[] = {NULL,NULL,NULL,NULL};
temp[0]="sum";
sprintf(*temp[1],"%f",x); //here I want to convert float number to char but it doesn't work
sprintf(*temp[2],"%f",y);
execv("sum",temp);
}
else
{
wait(NULL);
printf("parentPID: %d childPID: %d works now.\n", getpid(), pid);
}
return 0;
}
最佳答案
char command1[50], command2[50]; // Added
char *temp[] = {NULL, command1, command2, NULL}; // Modified
temp[0]="sum";
sprintf(temp[1],"%f",x); // remove *
sprintf(temp[2],"%f",y); // remove *
您没有alloc
ating temp[1]
和temp[2]
并将它们用作sprintf 中的目标缓冲区
并在 sprint 中使用了不正确的 *
。
您可以使用 malloc
分配此内存或使用其他字符串(如上例所示)来初始化数组。
来自Sourav Ghosh的亲切评论| :
在 sum.c
中,将以下代码行更改为:
if(argc!=3)
{
printf("error...\n");
return -1;
}
否则,它 may导致未定义的行为。
关于c - sprintf() 命令不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28963520/