字符串数组转换

发布于 2024-12-11 00:04:10 字数 540 浏览 2 评论 0原文

我有以下代码:

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:

string array initialisation

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

少女七分熟 2024-12-18 00:04:10

对我来说似乎完全合法; char *[3] 衰减为 char **,因此分配应该有效。

GCC 4.4.5 和 CLang 1.1 都没有抱怨。

Seems perfectly legal to me; char *[3] decays to char **, so the assignment should be valid.

Neither GCC 4.4.5 nor CLang 1.1 complains.

臻嫒无言 2024-12-18 00:04:10

尽管实际上 array1 应该衰减为 char ** 类型的指针,但它的真实类型实际上是 char *[3],因此警告。

要抑制警告,您可以尝试显式转换它:

...
(char **) array1;
...

Although in practice array1 should decay to a pointer of type char **, its real type is in fact char *[3], hence the warning.

To suppress the warning, you could try casting it explicitly:

...
(char **) array1;
...
把时间冻结 2024-12-18 00:04:10

array1 是 (char *)[3],它在语义上与 char ** 不同,尽管在赋值中它应该被优雅地降级为 char **

array1 is (char *)[3], which is semantically different from char **, although in the assignment it should be gracefully degraded to a char **

不甘平庸 2024-12-18 00:04:10

指针和数组仅在静态范围内兼容。在全局范围内,指针和数组不同,混合两者将导致未定义的行为。所以在我看来,这个警告是正确的。

尝试将:

extern char *array1[3] = 
{
    "hello",
    "world",
    "there."
};

放入一个模块并:

extern char **array1;

struct locator_t
{
    char **t;
    int len;
} locator[2] =
{
    {
        array1,
        10
    }
};

放入另一个模块中,进行编译和链接。 (我还没试过……)我预计事情会出错……

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:

extern char *array1[3] = 
{
    "hello",
    "world",
    "there."
};

in one module and:

extern char **array1;

struct locator_t
{
    char **t;
    int len;
} locator[2] =
{
    {
        array1,
        10
    }
};

in another, compile and link. (I haven't tried it…) I would expect things to go wrong...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文