我昨天在大学考试中遇到了这个问题/作业。它是这样的:
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/