字符串数组转换
我有以下代码:
char *array1[3] =
{
"hello",
"world",
"there."
};
struct locator_t
{
char **t;
int len;
} locator[2] =
{
{
array1,
10
}
};
它可以使用“gcc -Wall -ansi -pedantic”编译。但对于另一个工具链(Rowley),它会抱怨
warning: initialization from incompatible pointer type
char **t 所在的行。这确实是非法代码还是可以?
感谢您的所有回答。我现在知道我的问题出在哪里了。然而,它提出了一个新问题:
I have the following code:
char *array1[3] =
{
"hello",
"world",
"there."
};
struct locator_t
{
char **t;
int len;
} locator[2] =
{
{
array1,
10
}
};
It compiles OK with "gcc -Wall -ansi -pedantic". But with another toolchain (Rowley), it complains about
warning: initialization from incompatible pointer type
on the line where char **t is. Is this indeed illegal code or is it OK?
Thanks for all the answer. I now know where my problem was. However, it raises a new question:
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
对我来说似乎完全合法;
char *[3]
衰减为char **
,因此分配应该有效。GCC 4.4.5 和 CLang 1.1 都没有抱怨。
Seems perfectly legal to me;
char *[3]
decays tochar **
, so the assignment should be valid.Neither GCC 4.4.5 nor CLang 1.1 complains.
尽管实际上
array1
应该衰减为char **
类型的指针,但它的真实类型实际上是char *[3]
,因此警告。要抑制警告,您可以尝试显式转换它:
Although in practice
array1
should decay to a pointer of typechar **
, its real type is in factchar *[3]
, hence the warning.To suppress the warning, you could try casting it explicitly:
array1 是
(char *)[3]
,它在语义上与char **
不同,尽管在赋值中它应该被优雅地降级为char **
array1 is
(char *)[3]
, which is semantically different fromchar **
, although in the assignment it should be gracefully degraded to achar **
指针和数组仅在静态范围内兼容。在全局范围内,指针和数组不同,混合两者将导致未定义的行为。所以在我看来,这个警告是正确的。
尝试将:
放入一个模块并:
放入另一个模块中,进行编译和链接。 (我还没试过……)我预计事情会出错……
Pointers and arrays and only compatible in static scope. In global scope a pointer and an array are not the same, mixing the two will result in undefined behavior. So in my opinion, the warning is correct.
Try putting:
in one module and:
in another, compile and link. (I haven't tried it…) I would expect things to go wrong...