c - 如何将 char ** 转换为 c 中的 char *[]?

标签 c pointers c-strings execv

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/

相关文章:

c - Swift调用C API时如何处理指针

Java:JNA SystemParametersInfo 参数类型

c++ - 带有 const char* 的奇怪 std::cout 行为

c - fdim 首字母缩写词代表什么?

c - 从 C 中的 wav 文件中删除暂停

cgtk警告: initialization makes integer from pointer

c - 为什么即使我没有尝试修改字符串,C 中的字符串也会被修改?

C 字符串赋值给出段错误

c - 按字母顺序排序双向链表

c - Makefile目标文件生成、变量替换等问题