car
和_car
都是数组,并且不能在 C 中分配数组(除非数组嵌入在结构(或联合)中并且您执行结构分配)。
它们也是指向 char 的指针数组,而不是指向 char 数组的指针。您在代码中编写的内容可能就是您想要的 - 您可以在数组中存储指向最多 MAXINT 个名称的指针。但是,您应该正确描述类型 - 作为指向 char 或 char 指针的指针数组。
指向字符数组的指针如下所示:
char (*car)[MAXINT];
指向字符指针数组的点(谢谢,Brian)看起来像:
char *(*car)[MAXINT];
小心 MAXINT;这可能是一个非常大的数组(在 Linux 上,<values.h>
定义MAXINT
为INT_MAX
,至少为 2 31 -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 *
'),它会向各种滥用代码敞开大门。