小编Kai*_*hen的帖子

我应该何时通过值传递或返回结构?

结构可以通过值传递/返回,也可以通过C中的引用(通过指针)传递/返回.

普遍的共识似乎是,在大多数情况下,前者可以适用于没有惩罚的小结构.请参阅是否存在直接返回结构的良好做法?是否有任何缺点由值用C传递结构,而不是传递指针?

从速度和清晰度的角度来看,避免取消引用可能是有益的.但什么算?我想我们都同意这是一个小结构:

struct Point { int x, y; };
Run Code Online (Sandbox Code Playgroud)

我们可以通过相对有罪不罚的价值来传递:

struct Point sum(struct Point a, struct Point b) {
  return struct Point { .x = a.x + b.x, .y = a.y + b.y };
}
Run Code Online (Sandbox Code Playgroud)

那个Linux task_struct是一个大型结构:

https://github.com/torvalds/linux/blob/b953c0d234bc72e8489d3bf51a276c5c4ec85345/include/linux/sched.h#L1292-1727

我们希望不惜一切代价避免使用堆栈(特别是那些8K内核模式堆栈!).但是什么是中等的?我假设小于寄存器的结构是好的.但那些呢?

typedef struct _mx_node_t mx_node_t;
typedef struct _mx_edge_t mx_edge_t;

struct _mx_edge_t {
  char symbol;
  size_t next;
};

struct _mx_node_t {
  size_t id;
  mx_edge_t edge[2];
  int action;
};
Run Code Online (Sandbox Code Playgroud)

确定结构是否足够小以确定是否可以安全地通过值传递(缺少某些深度递归等情有可原的情况),最好的经验法则是什么?

最后请不要告诉我需要个人资料.当我太懒的时候,我要求使用启发式方法/它不值得进一步调查.

编辑:到目前为止,根据答案我有两个后续问题:

  1. 如果结构实际上小于指向它的指针怎么办? …

c shallow-copy

42
推荐指数
5
解决办法
1万
查看次数

有没有更好的计算方法(n*8 + 3)/ 5?

我需要拿一个size_t volume并计算这个结果size_t:

size_t next = (volume * 8 + 3) / 5
Run Code Online (Sandbox Code Playgroud)

如果这个结果会溢出,size_t那么next应该为零.问题当然是volume * 8 + 3溢出,而整个结果适合于size_t.

目前我正在拆分最后4位volume并分别执行乘法,加法和除法.我的问题是:如果没有比这更大的类型,我能做得比目前为止做得更好size_t吗?

size_t next_volume(size_t volume) {
  // check if the numerator will overflow size_t
  if (volume > (SIZE_MAX - 3) / 8) {
    size_t lower, upper;

    // multiply lower 4 bits by 8 and add 3
    lower = ((volume & 0xF) * 8) + 3;
    // downshift …
Run Code Online (Sandbox Code Playgroud)

c

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

标签 统计

c ×2

shallow-copy ×1