【问题标题】:Pointer illegal access to array on PIC32指针非法访问 PIC32 上的数组
【发布时间】:2021-06-23 01:20:23
【问题描述】:

我正在做一个项目,我需要访问一个代表 LCD 字体的 unsigned char 数组。有些字体需要两到三个字节来表示每一行。所以我试图实现这样的代码

const unsigned char font[]={...};//array of n bytes representing a font.
uint8_t *ptr = (uint8_t*)font;
void lcd_map(){
    //get 4 bytes of array as int to map LCD
    int val = *(int*)ptr;
}

将指针解引用为 int 不起作用,调试代码会导致类型非法访问地址的异常。

经过一些实验,当指针的分配和取消引用在同一范围内完成时,我得到了它的工作:

const unsigned char font[]={...};//array of n bytes representing a font.
uint8_t *ptr;
void lcd_map(){
    //get 4 bytes of array as int to map LCD
    ptr = (uint8_t*)font;
    int val = *(int*)ptr; 
}

但我需要将函数实现为以前的代码。可能是什么问题?我在在线 C 编译器上测试了之前的代码,它可以正常工作。

【问题讨论】:

  • 我的一般建议是不要将自己归类为一种实现。这成为社区的 X/Y 问题。相反,陈述你的意图并展示你做了什么。然后,您可能会得到更好的建议并学习解决问题的其他方法。
  • 将指针取消引用为int 不起作用因为这样做总是a strict aliasing violation 和未定义的行为。教你写这样的代码的人并不真正理解 C。你不能把内存当作它不是的东西(除非你总是可以把任何东西当作[un[signed]] char)。在这种情况下,您尝试将实际上是unsigned char 的内存视为int。 你不能安全地做到这一点。句号。任何告诉你的人都是完全错误的。
  • const unsigned char font[] 缺少某些 int 对齐。第 1 步:根据@Rafael 修复该问题。
  • 谢谢,我没有考虑严格的别名。相反,我使用memcpy() 并解决了问题。

标签: c pointers exception pic32


【解决方案1】:

我的建议是创建一个联合,允许您访问单个字节以及 4 字节整体:

union {
        uint32_t whole;
        uint8_t parts[4];
} font;

void lcd_map(void)
{
        uint32_t data = font.whole;
        uint8_t byte2 = font.parts[1];
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-03
    • 1970-01-01
    • 1970-01-01
    • 2016-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多