【问题标题】:Casting to array of pointers in C99在 C99 中转换为指针数组
【发布时间】:2015-12-01 17:58:17
【问题描述】:

我目前正在编写一个复杂的函数,这让我花了很多时间来构思。这个函数使用了一个类型为“struct foo*”的数组,它之前是这样定义的:

struct foo** array_of_pointers = NULL;

为了让代码更容易理解,我决定将定义改为:

struct foo* array_of_pointers[] = {NULL};

(赋值是为了使它成为一个强符号)

但现在问题就在这里:

array_of_pointers = (?) calloc(256, sizeof(struct foo*));

直觉上,我将“?”替换为“struct foo* []”。这看起来很奇怪,实际上会导致编译器错误:“cast指定数组类型”。

所以我的问题是:有谁知道应该放置什么而不是“(?)”?

【问题讨论】:

标签: c arrays pointers casting


【解决方案1】:

在这里,您要声明一个类型为 struct foo* 的数组,其中包含一个元素(因为未指定大小 []),并且该元素是 NULL

struct foo* array_of_pointers[] = {NULL};

它指向的地址不能更改,如:

array_of_pointers = calloc(256, sizeof(struct foo*));  
// wrong, doesn't compile and casting the return of calloc won't help

这与声明指向 struct foo* 的指针时不同,如下所示:

struct foo** array_of_pointers = NULL;

你只能分配给后者。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-07
    • 2021-04-12
    • 1970-01-01
    相关资源
    最近更新 更多