c - 使用铸件缩放结构元素

标签 c pointers struct

我昨天在大学考试中遇到了这个问题/作业。它是这样的:

Give the following structure:

typedef struct _rect {
     int width;
     int height;
} rect;

How could you scale the width and height members using a cast to int* without explicitly accessing the two members?

所以基本上,给定那个结构,我该怎么做

rect *my_rectangle = malloc(sizeof(rect));
my_rectangle->width = 4;
my_rectangle->height = 6;

// Change this part
my_rectangle->width /= 2;
my_rectangle->height /= 2;

使用强制转换为 int 或 int*?

最佳答案

您只能可靠地扩展第一个成员:

*((int *) my_rectangle) /= 2;

这并不违反严格的别名规则,因为标准明确允许将指向结构对象的指针转换为其第一个成员的指针。

C11 §6.7.2.1/15 Structure and union specifiers

Within a structure object, the non-bit-field members and the units in which bit-fields reside have addresses that increase in the order in which they are declared. A pointer to a structure object, suitably converted, points to its initial member (or if that member is a bit-field, then to the unit in which it resides), and vice versa. There may be unnamed padding within a structure object, but not at its beginning.

假设这些成员之间没有填充,第二个成员也可以缩放,只要指针与成员的类型相同(兼容),即 int.

关于c - 使用铸件缩放结构元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42784484/

相关文章:

编译器不执行代码块中的程序

使用 C 中的指针将数组的内容复制到多维数组?

c - 如何从链表中获取字符串的第一个字符?

c++ - 不确定如何处理析构函数(类中的大型顶点数组用作同一类的其他实例的数据源)

function - 结构嵌入、函数输入、多态性

c++ - 为什么我不能正常初始化 typedef struct string 或 char?

c - 双尾递归需要解释

c - 从字符串中获取最后一个单词

python - C-Python 扩展中的全局 PyObject* 变量

c++ - 从函数返回时指针损坏