Typedef 结构到结构数组

typedef structure to array of structures

本文关键字:结构 数组 Typedef      更新时间:2023-10-16

我确定这是一个脑子放屁,但我错过了一些东西,谷歌搜索似乎没有带来任何东西。

struct item
{
   int a;
   int b;
   int c;
};
typedef item *itemcatalog;

所以"itemcatalog"只是"item"的数组。

const item items[] = {{1,2,3},{4,5,6}};
const item *collection = items; // OK
const itemcatalog catalog = items; // "item const *" is incompatible with "itemcatalog"

这个想法是"itemcatalog"更具描述性,并显示需要一组项目,而不仅仅是指向单个项目的指针。

编辑:修复错别字。

首先,有一个错别字:

在失败的行上,您忘记命名对象。

const itemcatalog collection2 = items;

现在,让我们也尝试将 const 限定符应用于这些变量:

当我们这样做时,我们仍然会收到一个错误:

foo.cc:14:19: error: cannot initialize a variable of type 'const itemcatalog' (aka 'item *const') with an lvalue of type 'const item [2]'
const itemcatalog catalog = items;
                  ^         ~~~~~
1 error generated.

为了解决这个问题,我们需要意识到在这种情况下我们实际上需要两个 typedef:

struct item
{
    int a;
    int b;
    int c;
};
typedef item *itemcatalog;
typedef const item *constitemcatalog;
const item items[] = {{1,2,3},{4,5,6}};
const item *collection = items;
const constitemcatalog collection2 = items;
item mutable_items[] = {{1,2,3},{4,5,6}};
const item *collection3 = mutable_items;
const itemcatalog collection4 = mutable_items;

在各种集合对象上,我们应用const告诉我们是否可以移动指针。 constitemcatalog vs itemcatalog 告诉我们是否可以修改指针指向的数据。