【问题标题】:expected ‘char **’ but argument is of type ‘char *’ --argv预期为“char **”,但参数的类型为“char *”--argv
【发布时间】:2013-09-25 16:53:10
【问题描述】:

我正在尝试创建一个简单的 shell,它接受“ls”或“ls -l”之类的内容并为我执行它。

这是我的代码:

#include <stdio.h>
#include <sys/wait.h>
#include <unistd.h> 
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>

void execute(char **argv)
{
  int status;
  int pid = fork();
  if ((pid = fork()) <0)
     {
       perror("Can't fork a child process\n");
       exit(EXIT_FAILURE);
     }
  if (pid==0)
     {
    execvp(argv[0],argv);
        perror("error");
     }
  else
     {
      while(wait(&status)!=pid) 
         ;
     }


}

int main (int argc, char **argv)

{

   char args[256];
   while (1)
   {
      printf("shell>");
      fgets(args,256,stdin);
      if (strcmp(argv[0], "exit")==0)
             exit(EXIT_FAILURE);
      execute(args);
   }

}

我收到以下错误:

basic_shell.c: In function ‘main’:
basic_shell.c:42: warning: passing argument 1 of ‘execute’ from incompatible pointer type
basic_shell.c:8: note: expected ‘char **’ but argument is of type ‘char *’

能否请您指点一下如何正确地将参数传递给我的执行函数?

【问题讨论】:

  • 每当我看到有人要求指点我记得xkcd漫画...

标签: c shell process argv


【解决方案1】:

现在,您将单个字符串传递给execute(),它需要一个字符串数组。您需要将args 分解为组件参数,以便execute() 可以正确处理它们。 strtok(3) 可能是一个不错的起点。

【讨论】:

    【解决方案2】:

    note: expected ‘char **’ but argument is of type ‘char *’ 说明一切。

    你还需要什么?

    args 正在衰减到 char *,但你有 char ** 对应 void execute(char **argv)

    您需要将您的args 拆分为

    • 命令
    • 选项

    使用strtok函数

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-12-04
      • 2020-07-31
      • 2023-04-08
      • 1970-01-01
      • 1970-01-01
      • 2016-11-01
      • 1970-01-01
      相关资源
      最近更新 更多