0

用于 msp430 的 IAR 嵌入式工作台。选择C标准99

您好,我是指针新手,卡在一个地方。这是代码的一部分:

void read_SPI_CS_P2(uint8_t read_from, int save_to, uint8_t bytes_to_read)
{
        uint8_t * ptr;
        ptr = save_to;
...

从我读到的关于指针的内容中,我假设:

uint8_t * ptr; - 这里我声明了数据指针指向的类型(我想保存 uint8_t 值)

ptr = save_to; - 在这里我分配我想写入的内存地址(它是 0xF900 所以 int)

它给了我一个错误[Pe513]:“int”类型的值不能分配给“uint8_t *”类型的实体

问题是……为什么?将要保存的数据大小(到 save_to)和内存地址的大小不能不同吗?

4

2 回答 2

0

C language has no immediate feature that would allow you to create pointers to arbitrary numerical addresses. In C language pointers are obtained by taking addresses of existing objects (using unary & operator) or by receiving pointers from memory allocation functions like malloc. Additionally, you can create null pointers. In all such cases you never know and never need to know the actual numerical value of the pointer.

If you want to make your pointer to point to a specific address, then formally the abstract C language cannot help you with it. There's simply no such feature in the language. However, in the implementation-dependent portions of the language a specific compiler can guarantee, that if you forcefully convert an integral value (containing a numerical address) to pointer type, the resultant pointer will point to that address. So, if in your case the numerical address is stored in save_to variable, you can force it into a pointer by using an explicit cast

ptr = (unit8_t *) save_to;

The cast is required. Assigning integral values to pointers directly is not allowed in standard C. (It used to be allowed in pre-standard C though).

A better type to store integral addresses would be uintptr_t. int, or any other signed type, is certainly not a good choice for that purpose.

P.S. I'm not sure what point you are trying to make when you talk about sizes. There's no relation between the "size of data that will be saved" and size of memory address. Why?

于 2013-10-09T05:20:49.180 回答
0

从语法的角度来看,您可以将 int 直接转换为更改其值的指针。但在这种情况下,这可能不是一个好主意或对你有帮助的东西。

您必须使用编译器和链接器支持来指示他们您希望在内存中的特定位置获取一些数据。通常,您可以使用#pragma location语法(使用 IAR 工具链)执行此操作,例如:

__no_init volatile uint8_t g_u8SavingLocation @ 0xF900;

您不能简单地在内存中设置指针的值并开始在该位置写入。链接器负责决定内容在内存中的位置,您可以使用#pragma 和链接器设置文件指示您想要实现的目标。

于 2013-10-09T04:46:38.297 回答