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

时间:2014-03-23 18:03:20

标签: 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,我会收到错误地址错误。

2 个答案:

答案 0 :(得分:1)

来自execv手册页:

&#34;指针数组必须用NULL指针终止。&#34;

函数execv不知道参数计数

 char **list = malloc((argc+1)*sizeof(char*));
 if (list == NULL) {
     abort();
 }
 int i;
 for(i=0;i<argc;++i){ // using argv for example...
     if ((list[i] = strdup(argv[i])) == NULL) {
         abort();
     }
 }
 list[argc] = NULL;
 execv(list[0], list);

EDIT 我还从execv调用中删除了list + 1,感谢@ajay找到它

答案 1 :(得分:1)

标题execv中声明的函数unistd.h的签名是

int execv(const char *path, char *const argv[]);

请注意,这与

相同
int execv(const char *path, char *const *argv);

表示argv是指向char * const类型对象的指针,即指向字符的常量指针。另外,execv的手册页说 -

  

按照惯例,第一个参数应该指向文件名   与正在执行的文件相关联。指针数组必须   被NULL指针终止。

此外,list的类型为char **,与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);
相关问题