[英]execvp and type of parameters - ansi c
I am having trouble with using execvp()
. 我在使用execvp()
时遇到问题。 execvp()
expects type char * const* as second parameter. execvp()
期望类型char * const *作为第二个参数。 I want to parse arguments passed to application (in argv
) and make an array of that type. 我想解析传递给应用程序的参数(在argv
)并创建该类型的数组。 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 ? 怎么做正确 ?
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". 问题是execvp
的第二个参数是char * const *
,它是“指向非常量数据的常量指针的指针”。 You're trying to pass it a const char **
, which is a "pointer to a pointer to constant data". 你试图传递一个const char **
,这是一个“指向常量数据的指针”。
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 **
而不是const char **
(因为“指向X的指针”始终允许转换为“指向const
X的指针”,对于任何类型X(但仅限于顶层)指针):
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. 请注意,如果您确实需要插入const char *
参数,只要不修改它们就可以将它们转换为char *
。 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 ). 尽管exec*
函数族的参数被声明为非const
,但它们不会修改它们(参见POSIX 2008规范 )。 The rationale there explains why they are declared as non- const
. 那里的基本原理解释了为什么它们被声明为非const
。
You can just use char *p[10]
. 你可以使用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. 要将其分解: char *const *p
表示“非恒定字符的常量指针的非常量指针” - 也就是说, p
是可写的, p[0]
是不可写的,并且p[0][0]
是可写的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.