繁体   English   中英

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

[英]How do I convert char ** to a char *[] in c?

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我会收到错误的地址错误。

来自execv手册页:

“指针数组必须以NULL指针终止。”

函数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);

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

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

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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM