execv
函数将指针数组作为第二个参数。我有一个指向指针的指针,一个动态创建的字符串列表。
我如何从中创建一个指针数组?
char **list = malloc((argc)*sizeof(char*));
int i=0;
for(i=0;i<argc;++i){ // using argv for example...
list[i] = malloc(strlen(argv[i])+1);
strcpy(list[i], argv[i]);
}
// create from list an array of pointers
execv(list_pointers[0], list_pointers);
否则,如果将 list
简单地传递给 execv
,我会得到一个 Bad address 错误。
最佳答案
在 header unistd.h
中声明的函数execv
的签名是
int execv(const char *path, char *const argv[]);
请注意,这与
相同int execv(const char *path, char *const *argv);
这意味着 argv
是一个指向 char * const
类型对象的指针,即一个指向字符的常量指针。此外,execv
的手册页说 -
The first argument, by convention, should point to the filename associated with the file being executed. The array of pointers must be terminated by a NULL pointer.
此外,类型为char **
的list
赋值与execv
的第二个参数兼容。我建议进行以下更改 -
// +1 for the terminating NULL pointer required for the
// second argument of execv
char **list = malloc((argc + 1) * sizeof *list);
if(list == NULL) {
printf("not enough memory to allocate\n");
// handle it
}
int i = 0;
for(i = 0; i < argc; ++i) {
// strdup returns a pointer to a new string
// which is a duplicate of the string argv[i]
// this does effectively the same as the commented
// out block after the below statement.
// include the header string.h for the prototype
// of strdup POSIX function.
list[i] = strdup(argv[i]);
/*
list[i] = malloc(strlen(argv[i])+1);
if(list[i] == NULL) {
printf("not enough memory to allocate\n");
// handle it
}
strcpy(list[i], argv[i]);
*/
}
list[argc] = NULL; // terminate the array with the NULL pointer
execv(list[0], list);
关于c - 如何将 char ** 转换为 c 中的 char *[]?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22594841/