car 和 _car 都是数组,您不能在 C 中分配数组(除非数组嵌入在结构(或联合)中并且您执行结构分配)。
它们也是指向 char 的指针数组,而不是指向 char 数组的指针。您在代码中编写的内容可能就是您想要的 - 您可以在数组中存储指向最多 MAXINT 个名称的指针。但是,您应该正确地描述类型 - 作为指向 char 或 char 指针的指针数组。
指向字符数组的指针如下所示:
char (*car)[MAXINT];
指向字符指针数组的点(谢谢,Brian)如下所示:
char *(*car)[MAXINT];
小心 MAXINT;这可能是一个非常大的数组(在 Linux 上,<values.h> 将 MAXINT 定义为 INT_MAX,至少为 231-1)。
代码如下:
struct foo
{
int _bar;
char * _car[MAXINT];
}
int foofunc (void * arg)
{
int bar;
char * car[MAXINT];
struct foo thing = (struct foo *) arg;
bar = arg->_bar; // this works fine
car = arg->_car; // this gives compiler errors of incompatible types in assignment
}
对 bar 和 car 的赋值都不应该编译 - arg 是 void *。您大概打算以某种形式或形式使用thing。正如 Brian 指出的那样,那里也存在问题:
你要么想要:
int foofunc(void *arg)
{
int bar;
char *car[MAXINT];
struct foo thing = *(struct foo *)arg;
bar = thing._bar; // this works fine
car = thing._car; // this is still an array assignment
...other code using bar and car...
}
或者你想要的:
int foofunc(void *arg)
{
int bar;
char *car[MAXINT];
struct foo *thing = (struct foo *) arg;
bar = thing->_bar; // this works fine
car = thing->_car; // this is still an array assignment
...other code using bar and car...
}
或者,确实:
int foofunc(void *arg)
{
struct foo *thing = (struct foo *) arg;
int bar = thing->_bar; // this works fine
char *car[MAXINT] = thing->_car; // this is still an array assignment
...other code using bar and car...
}
最后,处理数组赋值,在C中你可以合理地使用memmove()来做到这一点:
int foofunc(void *arg)
{
struct foo *thing = (struct foo *) arg;
int bar = thing->_bar; // this works fine
char *car[MAXINT];
memmove(car, thing->_car, sizeof(car));
...other code using bar and car...
}
如果要复制的区域重叠,类似的函数memcpy()没有可靠的语义,而memmove()有;始终使用memmove() 会更简单,因为它始终可以正常工作。在 C++ 中,您需要谨慎使用memmove()(或memcpy())。在这段代码中,它已经足够安全了,但理解其中的原因并非易事。
您确实需要注意,您只是在此处复制指针 - 您不是在复制指针指向的字符串。如果有其他东西改变了这些字符串,它会影响通过car 看到的值和调用代码中的变量。
最后一点 - 现在:您确定需要将函数的参数作为 void * 吗?如果将函数声明为采用“struct foo *”(甚至是“const struct foo *”),它会向各种滥用代码敞开大门。