car
and _car
都是数组,并且不能在 C 中分配数组(除非数组嵌入到结构(或联合)中并且执行结构分配)。
它们也是指向 char 的指针数组,而不是指向 char 数组的指针。您在代码中编写的内容可能就是您想要的 - 您可以在数组中存储最多 MAXINT 名称的指针。但是,您应该正确地描述类型 - 作为指向 char 或 char 指针的指针数组。
指向字符数组的指针如下所示:
char (*car)[MAXINT];
指向字符指针数组的点(谢谢,Brian)看起来像:
char *(*car)[MAXINT];
Be careful of MAXINT; that could be a very large array (on Linux, <values.h>
defines MAXINT
as INT_MAX
, which is at least 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
is a void *
。你可能想使用thing
以某种形状或形式。正如布莱恩指出的,那里也存在问题:
您要么想要:
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()
(or memcpy()
)。在这段代码中,它足够安全,但理解其中的原因并非易事。
您确实需要注意,您只是在此处复制指针 - 您没有复制指针指向的字符串。如果其他东西改变了这些字符串,它会影响通过看到的两个值car
以及调用代码中的变量。
最后一点 - 现在:您确定需要将函数的参数作为void *
?它使代码容易遭受各种滥用,如果函数被声明为采用 'struct foo *
' 代替(或者甚至是 'const struct foo *
').