c - 将 char[][] 传递给 execvp 时出现问题

标签 c

我正在尝试迭代一些输入(命令和参数),将输入拆分为单独的字符串,然后将该输入传递给 execvp()

我遇到了麻烦,因为 execvp() 想要一个 (char*, char*[]) 作为它的参数。我正在传递 (char*, char[][]) 我认为是同一件事,但它不喜欢它。

我会使用 char*[] 但我不知道在它运行之前字符串有多大,所以这就是我没有使用它的原因。所以很明显,如果我使用 char*[],当我尝试访问 char* 的元素时,我会遇到段错误。

这是代码片段

//input
char *line = "echo hello there what is";
int count = 0;

//store arguments
char args[6][10];
int argCount = 0;

//store temp string from input
char temp[100];
int tempCount = 0;

//word(string) size
int wordSize = 0;

/*
 Here I iterate over the input, storing each string I find in args
 all the above variables help me do that.
 */

execvp(args[0], args);

printf("Error: It didnt work\n");

希望这是一个清晰且有效的问题,如果您想让我添加将输入转换为 args 的代码,请告诉我。

最佳答案

char 数组的数组与指向char 数组的指针数组不同。 execvp() 期望后者以空指针作为其最后一个元素,传递前者具有未定义的行为。

你必须构造一个指针数组,要么从堆中分配,要么用自动存储定义(在堆栈上),用指向参数字符串的指针初始化它,并将这个数组传递给 execvp ()

另请注意,echo 既是 shell 内部命令,也是路径中的可执行文件。

这是您相应修改的代码片段(没有解析代码,仍然由您编写):

    //input "echo hello there what is";
    //arguments array
    char *args[6];

    /*
     * Here you should iterate over the input, storing each string you find 
     * on the command line into `args` and terminate with a null pointer...
     */

    args[0] = "echo";
    args[1] = "hello";
    args[2] = "there";
    args[3] = "what";
    args[4] = "is";
    args[5] = NULL;

    execvp(args[0], args);

关于c - 将 char[][] 传递给 execvp 时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55981330/

相关文章:

c - 使用 TCP 在 C 中发送两个字节

c++ - 生成唯一变量并重用它们

c++ - CPP : Writing gmail Mail Auto Reply program in CPP

c - 使用 fgets 和链表

c - 想知道一些#define 技巧

c - 在 Tiva C 中按下开关时 LED 闪烁

c - varargs 是否提供了一种穷人的多态性?

c - strstr() 函数的实现

c - Unix Sockets 的缓冲特性

c - 给定一个点和一个正方形面积值作为输入参数的函数返回四个正方形