相关疑难解决方法(0)

什么是严格别名规则?

当询问C中常见的未定义行为时,灵魂比我提到的严格别名规则更加开明.
他们在说什么?

c strict-aliasing undefined-behavior type-punning

778
推荐指数
10
解决办法
19万
查看次数

结构填料和包装

考虑:

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 structure packing padding

189
推荐指数
6
解决办法
25万
查看次数

用 C 编写“通用”结构打印方法

是否可以在 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方法:

  • 这可以吗?如果可以的话怎么做?
  • 在 C 中创建非特定类型函数被认为是好还是坏实践?

否则,代码中不会充斥着数十个(在大型项目中甚至数百个?)如下所示的函数:

void …
Run Code Online (Sandbox Code Playgroud)

c struct

1
推荐指数
1
解决办法
713
查看次数