I hit some code in Linux kernel:

static struct ctl_table ip_ct_sysctl_table[] = {
    {
        .procname   = "ip_conntrack_max",
        .maxlen     = sizeof(int),
        .mode       = 0644,
        .proc_handler   = proc_dointvec,
    },
    // ...
    {
        .procname   = "ip_conntrack_log_invalid",
        .maxlen     = sizeof(unsigned int),
        .mode       = 0644,
        .proc_handler   = proc_dointvec_minmax,
        .extra1     = &log_invalid_proto_min,
        .extra2     = &log_invalid_proto_max,
    },
    { }
};

Here an array of structs ends with { }. For what purpose was it added?
By the way, a bit above this code there is another array of structs, but without empty braces at the end.

When should I use empty braces at the end of an array of structs?

推荐答案

This particular change was part of the sysctl net: Remove unused binary sysctl code commit by Eric W. Biederman, changing the initialization of the last element of the ip_ct_sysctl_table array from {0} to {} (and performs similar changes to many other array initializations).

The {0} pattern seems to have been around for much longer though, and both {0} or {} final element-initialization is commonly (in the Linux source code) explicitly referred to as Terminating entry, so it is likely a pattern present to allow consuming these arrays without knowing their lengths, terminating consumption when hitting the zero-initialized terminating entry. E.g. for the similar arrays in sound/aoa/fabrics/snd-aoa-fabric-layout.c the intent of the zero-initialization is even explicitly mentioned in a comment, e.g.:

static struct codec_connection toonie_connections[] = {
  {
      .connected = CC_SPEAKERS | CC_HEADPHONE,
      .codec_bit = 0,
  },
  {} /* terminate array by .connected == 0 */
};

C++相关问答推荐

C sscanf没有捕获第二个参数

使用SWI—Prolog的qsave_program生成二进制文件有什么好处?'

什么C代码将确定打开的套接字正在使用的网络适配器?

如何判断宏参数是否为C语言中的整型文字

为什么输出不是从上到下C

在C中将通用字符名称转换为UTF-8

为什么I2C会发送错误的数据?

当我更改编译优化时,相同的C代码以不同的方式运行

为什么GDB/MI进程的FIFO循环中有read()阻塞

是否可以使用指针算法在不对齐的情况下在 struct 中相同类型的字段的连续序列之间移动?

struct -未知大小

如何在下面的C代码中正确管理内存?

为什么数组的最后一个元素丢失了?

如何在C中使数组变量的值为常量?

通过描述符查找文件路径时出现问题

';\n&39;和';\r&39;中的';\n&39;之间有什么关系?

将多项式从文件.txt加载到终端时出现问题

如何在zOS上编译共享C库

宏观;S C调深度

cs50拼写器分配中的无限循环