【问题标题】:sprintf() command doesnt worksprintf() 命令不起作用
【发布时间】:2015-03-10 12:17:22
【问题描述】:

我正在尝试编写一个 c 程序,它从用户那里获取两个浮点数,然后使用 execv() 命令调用另一个程序。但我不能这样做,因为将 float 转换为 char 或者我不知道为什么。 问题是 execv() 命令不起作用;输出一定是这样的

输入第一个数字:5
输入第二个数字:7
5.000000 + 7.000000 = 12.000000
parentPID: 9745 childPID: 9746 现在可以使用

但现在是这样

输入第一个数字:5
输入第二个数字:7
parentPID:9753 childPID: 9754 现在可以使用了

我的第一个 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;
}

【问题讨论】:

  • “我做不到”到底是什么意思?实际问题是什么?请澄清。

标签: c arrays execv


【解决方案1】:
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 *

你不是 allocating 到 temp[1]temp[2] 并在 sprintf 中使用它们作为目标缓冲区并在 sprint 中使用不正确的 *

您可以使用malloc 分配此内存或使用如上示例中所示的其他字符串来初始化数组。


来自Sourav Ghosh的善意评论:

sum.c 中,将以下代码行更改为:

if(argc!=3)
{
  printf("error...\n");
  return -1;
}

否则,may 会导致未定义的行为。

【讨论】:

  • @MohitJain 先生,请在if(argc!=3) 的第一个代码中提及退出或返回语句的要求。否则使用argv[1]等可能导致UB。
  • 您遇到什么错误?您是否进行了我建议的所有 4 项更改并正确重新编译。我建议使用 gcc -W -Wall -O2 标志进行编译。
  • @SouravGhosh 谢谢。随时可以编辑我的答案。
  • 谢谢@MohitJain,在 Sourav Ghosh 发表评论后,它现在可以工作了 :)
猜你喜欢
  • 1970-01-01
  • 2014-09-28
  • 2023-04-08
  • 2018-11-14
  • 2012-08-27
  • 2014-11-25
  • 2016-12-11
  • 2018-12-18
  • 2018-02-25
相关资源
最近更新 更多