3

我正在使用 Microchip C18 编译器做一个项目。我有一个称为块的结构,它指向其他块(东北西南)。这些块将使我成为一张地图。然后我有一个指针,我用它来评估一切。

仅使用 RAM,它看起来像:

struct block{
        struct block *north;
        struct block *east;
        struct block *south;
        struct block *west;
};


struct block map[5] =
{ // just a simple line.
        { NULL, &map[1], NULL, NULL },
        { NULL, &map[2], NULL, &map[0]},
        { NULL, &map[3], NULL, &map[2]},
        { NULL, &map[4], NULL, &map[3]},
        { NULL, NULL, NULL, &map[4]}
};


struct block* position = &map[0];

这让我可以做类似的事情:

void goWest()
{
if(position -> west != NULL) position = position -> west;
}

问题是我的项目中的 RAM 用完了,需要使用 ROM 我目前拥有的是:

struct block{
        rom struct block *north;
        rom struct block *east;
        rom struct block *south;
        rom struct block *west;
};
rom struct block map[5] =
{ // just a simple line.
        { NULL, &map[1], NULL, NULL },
        { NULL, &map[2], NULL, &map[0]},
        { NULL, &map[3], NULL, &map[2]},
        { NULL, &map[4], NULL, &map[3]},
        { NULL, NULL, NULL, &map[4]}
};

我已经做了一些调试,可以告诉上面的部分工作,但试图使位置指针让我很伤心。所以我想我的问题是:

如何将 ROM 变量地址保存在可以编辑其值的指针中?

当我尝试:

struct block *position = &map[0];

我收到“警告 [2066] 分配中的类型限定符不匹配”

我意识到 ROM 变量和 RAM 变量是两个不同的东西,但我不知道该怎么做。

4

1 回答 1

4

rom宏的定义是什么?我猜它会扩展为const(可能是特定于编译器的__attribute__或类似的),因为编译器抱怨“类型限定符不匹配”,它指的是 aconstvolatile不匹配。

这意味着您正在尝试将指向常量数据的指针隐式转换为指向非常量数据的指针。此代码应使用您的编译器生成相同的警告:

const int x = 0;
int *y = &x;  // &x is "pointer to const" but y is "pointer to non-const"

要修复它,您需要声明您的position指针是指向常量数据的指针(根据rom宏的定义,应该使用romor 或const限定符来完成):

// Declare a non-constant pointer to constant data
const struct block *position = &map[0];

在每个指针级别,您可以有一个const限定符或缺少限定符,对于基本非指针对象也是如此。因此,单级指针可以有 4 种不同的变体:

int *x;  // Non-constant pointer to non-constant data
int *const x;  // Constant pointer to non-constant data
const int *x;  // Non-constant pointer to constant data
int const *x;  // Same as above
const int *const x;  // Constant pointer to constant data
int const *const x;  // Same as above

请注意int constconst int是等价的,但除此之外的位置const 确实很重要。

于 2012-11-20T23:56:36.800 回答