当询问C中常见的未定义行为时,灵魂比我提到的严格别名规则更加开明.
他们在说什么?
考虑:
struct mystruct_A
{
char a;
int b;
char c;
} x;
struct mystruct_B
{
int b;
char a;
} y;
Run Code Online (Sandbox Code Playgroud)
结构的尺寸分别为12和8.
这些结构是填充还是包装?
什么时候进行填充或包装?
是否可以在 C 中执行类似以下操作来打印不同但相似的struct类型?
#include<stdio.h>
typedef struct Car {
char* name;
unsigned int cost
} Car;
typedef struct Animal {
char* name;
unsigned int age;
unsigned int weight
} Animal;
void print_struct(void *obj) {
printf("The name is: %s\n", obj->name);
};
int main(void)
{
Animal *dog = & (Animal) {.name = "Dog", .age = 10, .weight = 200};
Car *ford = & (Car) {.name = "Ford", .cost = 50000};
print_struct(dog);
};
Run Code Online (Sandbox Code Playgroud)
具体来说,print_struct方法:
否则,代码中不会充斥着数十个(在大型项目中甚至数百个?)如下所示的函数:
void …Run Code Online (Sandbox Code Playgroud)