【问题标题】:pointer and type cast指针和类型转换
【发布时间】:2016-07-07 16:11:31
【问题描述】:

真假: 以下分配有效:

#define GIMME *(unsigned int**) 0x3000 
unsigned short d = 42; 
GIMME = &d;

这是错误的,尽管我无法理解为什么。我最近从 Java 转换为 C,因此我们将不胜感激。

【问题讨论】:

  • 如何定义“有效”?如果这些行在函数定义中,这似乎是正确的。整数0x3000会以实现定义的方式转换为指针,unsigned shortunsigned int可能有相同的对齐要求。
  • 你想做什么?
  • 这不是您要查找的代码。换一本好的 C 书吧。
  • @MikeCAT: 但是unsigned short *unsigned int * 是不同的类型,如果没有明确的演员表,你不能将一个分配给另一个。 GIMME 中的转换必须是 (unsigned short **),或者 &d 需要转换为 unsigned int *
  • 在措辞上说明这一点:没有显式/隐式转换,因为“转换”是隐式显式的。另一件事叫做“隐式转换”:char c = 'a'; int i = c; /* implicit conversion from char to int here */

标签: c pointers casting type-conversion


【解决方案1】:

代码正在尝试 2 件有问题的事情:

  1. 将数据分配给未知有效的一些位置 (3000)。

    *(unsigned int**) 0x3000  = &d;
    
  2. 尝试分配不兼容的类型。对齐可能会失败,因为unsigned short 可能比unsigned int 窄。 IOW,这两种类型可能有不同的最小对齐要求。

指向对象类型的指针可以转换为指向不同对象类型的指针。如果结果指针未正确对齐引用的类型,则行为未定义。 C11 §6.3.2.3 7

    // similar simplified example
    unsigned short d = 42; 
    unsigned int* gimme;
    gimme = &d;  // warning: assignment from incompatible pointer type

【讨论】:

    猜你喜欢
    • 2013-02-12
    • 2020-11-17
    • 1970-01-01
    • 2021-09-20
    • 2016-06-28
    • 1970-01-01
    • 2020-06-15
    • 2015-02-14
    相关资源
    最近更新 更多