From argv to execvp

So I have a problem I haven't been able to solve. I'm writing a C program that executes some OS functions via pipes. The execution is done with execvp(const char *file, char *const argv[]);.

In my main function I would like to take the whole line passed to the program (argv) except for the first char-array and pass it to grep. Everything works at the moment, but I keep getting the warning:

warning: initialization from incompatible pointer type [enabled by default]
const char* grep = argv;
                   ^

My code looks like following. In the clause if(1 < argc) i want to be able to send the argv with the first post modified to newPipeline on the same format as printenv, sort and less.

int main(int argc, char** argv, char **envp){

    const char* printenv[] = {"printenv", NULL, NULL};
    const char* sort[] = {"sort", NULL, NULL};
    const char* less[] = {"less", NULL, NULL};
    if(1<argc){
        argv[0] = "grep";
        const char* grep = argv; 
        const char* const* commands[] = {printenv, sort, grep, less, NULL};
        newPipeline((char* const**)commands, 0, STDIN_FILENO);
    }
    //FROM HERE ON IT WORKS
    else{
        const char* const* commands[] = {printenv, sort, less, NULL};
        newPipeline((char* const**)commands, 0, STDIN_FILENO);
    }
    if(signal(SIGCHLD, SIG_IGN) == SIG_ERR){
        perror("A problem with the children");
    }
    exit(0);
}

I know that the pointer types are wrong. Should I build up a completely new array for grep or should I, as I am trying to do now, cast pointers into the right kind of pointers. If the later, which pointers would that be?

Upvotes: 1

Views: 516

Answers (2)

Petr Skocik
Petr Skocik

Reputation: 60107

Your grep variable needs to be a pointer to an array of strings or an array of strings (not simply a string).

Something like:

argv[0] = "grep";
const char** grep = (const char**)argv; //make grep point to the modified char** argv;

should do it, or construct a new array:

const char* grep[argc+1]; 
grep[0] = "grep";
grep[argc]=NULL;
for(int i=1; i<argc; i++){
  grep[i] = argv[i];
}

BTW, I believe you only need one NULL at the end of each string array.

Upvotes: 2

sameera sy
sameera sy

Reputation: 1718

The problem lies here

const char* grep = argv; 

C does not provide internal type casting for const types. And if your motive is to copy the array of argv into grep, it's wrong, use strcpy or any such function to make a clone of that array.

Upvotes: 1

Related Questions