Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

execvp and type of parameters - ansi c

I am having trouble with using execvp(). execvp() expects type char * const* as second parameter. I want to parse arguments passed to application (in argv) and make an array of that type. For example, user is invoking the binary as given below:

./myapp "ls -a -l"

And then I make the below array from it:

{"ls", "-a", "-l", NULL}

Now, my code looks like:

    const char* p[10];
    char temp[255] = "ls -a -l";

    p[0] = strtok(temp, " ");
    for(i=0; i<9; i++) {
        if( p[i] != NULL ) {
            p[i+1] = strtok(NULL, " ");
        } else {
            break;
        }
    }

It works, but I am getting the warning:

main.c:47: warning: passing argument 2 of ‘execvp’ from incompatible pointer type /usr/include/unistd.h:573: note: expected ‘char * const*’ but argument is of type ‘const char **’

How to do it correctly?

like image 957
marxin Avatar asked Oct 18 '12 18:10

marxin


2 Answers

You can just use char *p[10].

To break it down: char *const *p means "nonconstant pointer to constant pointer of nonconstant char" -- that is, p is writable, p[0] is not writable, and p[0][0] is writable.

like image 73
nneonneo Avatar answered Sep 27 '22 22:09

nneonneo


The problem is that the second parameter of execvp is a char * const *, which is a "pointer to a constant pointer to non-constant data". You're trying to pass it a const char **, which is a "pointer to a pointer to constant data".

The way to fix this is to use char ** instead of const char ** (since "pointer to X" is always allowed to be convert to "pointer to const X", for any type X (but only at the top level of pointers):

char* p[10];
p[0] = ...;
// etc.

Note that if you do need to insert const char * parameters, you can cast them char * as long as you don't modify them. Although the arguments to the exec* family of functions are declared as non-const, they won't ever modify them (see the POSIX 2008 specification). The rationale there explains why they are declared as non-const.

like image 22
Adam Rosenfield Avatar answered Sep 27 '22 23:09

Adam Rosenfield