【发布时间】:2016-02-22 08:15:30
【问题描述】:
在我使用gcc -Wall getopt.c -o options 编译并运行一些示例后,乍一看似乎可以正常工作。故意将其绊倒会导致 Segfault 错误。
//straight from the man page
static struct option long_options[] = {
{"add", required_argument, 0, 0 },
{"append", no_argument, 0, 0 },
{"delete", required_argument, 0, 0 },
{"verbose", no_argument, 0, 0 },
{"create", required_argument, 0, 'c'},
{"file", required_argument, 0, 0 },
{0, 0, 0, 0 } //<-- if i omit this line, it segfaults
};
为什么省略那一行会导致分段错误?
或者更确切地说,以不同的方式询问
为什么我必须将最后一组 struct option array 成员初始化为 null?
【问题讨论】:
-
您阅读文档了吗?
-
总是建议在抱怨之前阅读
man的功能。 -
我至少阅读了手册页 20 次。我的眼睛在这一点上是呆滞的。也许只是因为疲倦和睡不好,我认为你们中的任何人都没有真正理解我的问题。手册页从未说明原因。老实说,我不知道为什么。
-
@jargonjunkie 你的
why有一个明显的答案——因为函数需要知道列表的结束位置。最后一条记录作为终止符,它是 C 中的一个常见习惯用法 - 使用 0 或 NULL 终止符来表示列表的结尾,就像字符串一样
标签: c gnu glibc getopt getopt-long