How to add pointer to pointer array in C

65 Views Asked by At

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.

1

There are 1 best solutions below

3
On

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);
}