通过voidpointer传递char * args []

时间:2015-04-07 10:03:38

标签: c pointers void-pointers

她是我的简化代码:

void main(){
    void* ptr;
    char* args[3];
    args[0]="Arg1";
    args[1]="Arg2";
    args[2]="Arg3";
    ptr = &args;

    myMethod(ptr);
}
static void myMethod(void* args){

}

如何将void* args转换为char*[]?在myMethod(void*)

1 个答案:

答案 0 :(得分:6)

你想要一个指向char的指针:

#include <stdio.h>

static void myMethod(void *args)
{
    char **ptr = args;

    printf("%s\n", ptr[1]);
}

int main(void)
{
    void *ptr;
    char *args[3];

    args[0]="Arg1";
    args[1]="Arg2";
    args[2]="Arg3";
    ptr = args; /* You don't need the & */

    myMethod(ptr);
    return 0;
}

正如@Eregrith指出的那样,将单元格数传递给函数以防止越界访问:

#include <stdio.h>

static void myMethod(void *args, size_t elems)
{
    char **ptr = args;

    for (size_t i = 0; i < elems; i++)
        printf("%s\n", ptr[i]);
}

int main(void)
{
    void *ptr;
    char *args[3];

    args[0]="Arg1";
    args[1]="Arg2";
    args[2]="Arg3";
    ptr = args;

    myMethod(ptr, sizeof(args) / sizeof(args[0]));
    return 0;
}