如何将指针添加到C中的指针数组

发布于 2025-01-26 05:05:26 字数 324 浏览 3 评论 0原文

我正在尝试在C中创建一个简单的外壳。我在使用execve()函数时遇到问题。因此,我的论点被宣布为char *cmdargs [10];持有-A或-L等论点。但是,它与我的执行函数不起作用,我认为因为此数组没有命令作为第一个参数,因此我不确定如何将命令添加到数组的第一个。 假设现在的数组是

cmdargs[] = {"-a", "-l", NULL};

我想成为数组 cmdargs [] = {“ ls”,“ -a”,“ - l”,null}; 但是,该命令被声明为指针:char *cmd; 因此,我如何将此指针添加到数组的开始。

I am trying to create a simple shell in C. I am having issues with using the execve() function. So I have my arguments declared as char *cmdargs[10]; which holds the arguments such as -a or -l. However, it does not work with my execute function and I assume that because this array does not have the command as the first argument, and I am not sure how to add the command to the first of the array.
Assuming now the array is

cmdargs[] = {"-a", "-l", NULL};

I want to the array to be
cmdargs[] = {"ls", "-a", "-l", NULL};
However, the command is declare as a pointer: char *cmd;
so how I can add this pointer to the beginning of my array.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

暖心男生 2025-02-02 05:05:26

如果您的数组为 *cmdargs [] = {“ -a”,“ -l”,null},则可以做到这一点。

我在此处使用execv以简单:execve要求null终止的env数组作为最后一个参数

int main() {
    char *cmdargs[] = { "-a", "-l", NULL};

    int i = 0;
    while (cmdargs[i++])
        ;
//allocation of the size of a new array with one extra room
    char **tmp = malloc( sizeof(cmdargs) * ++i );
//add the path you need
    *tmp = "/bin/ls";
//null the end
    tmp[i] = NULL;
//copy what was on the previous
    i = -1;
    while (cmdargs[++i])
        tmp[i + 1] = cmdargs[i];
//use it..
    execv(tmp[0], tmp + 1);
}

Here is how you can do if your array is *cmdargs[] = {"-a", "-l", NULL};

I used execv here for simplicity: execve ask for a null terminated env array as last argument

int main() {
    char *cmdargs[] = { "-a", "-l", NULL};

    int i = 0;
    while (cmdargs[i++])
        ;
//allocation of the size of a new array with one extra room
    char **tmp = malloc( sizeof(cmdargs) * ++i );
//add the path you need
    *tmp = "/bin/ls";
//null the end
    tmp[i] = NULL;
//copy what was on the previous
    i = -1;
    while (cmdargs[++i])
        tmp[i + 1] = cmdargs[i];
//use it..
    execv(tmp[0], tmp + 1);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文