[英]Getopt and Optarg
Hi I am working on a Program in a book. 嗨,我正在写书中的程序。 The Program is working almost as it is supposed to, except for one mistake. 该程序几乎按照预期运行,除了一个错误。 Every time I try to use the "-l" case I get a Segmentation Fault. 每次我尝试使用“ -l”情况时,都会出现分段错误。 Any Ideas? 有任何想法吗?
#include <stdio.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
char *lieferung = "";
int knusprig = 0;
int zahl = 0;
char ch;
while ((ch = getopt(argc, argv, "l : k")) != EOF){
switch (ch) {
case 'l':
lieferung = optarg;
break;
case 'k':
knusprig = 1;
break;
default:
fprintf(stderr, "Unbekannte Option: '%s'\n", optarg);
return 1;
}
}
argc -= optind;
argv += optind;
if (knusprig)
puts("Knuspriger Rand.");
if (lieferung[0])
printf("Zu liefern: %s.\n", lieferung);
puts("Zutaten:");
for (zahl = 0; zahl < argc; zahl++)
puts(argv[zahl]);
return 0;
}
Thanks in advance. 提前致谢。
The third argument get getopt
shouldn't contain any spaces. 第三个参数getopt
不应包含任何空格。 Because there are spaces, it reads this argument as "-l takes no argument, -(space) takes an argument, -(space) takes no argument, and -k takes no argument. 因为存在空格,所以它将读取此参数,因为“ -l不带参数,-(space)带参数,-(space)不带参数,-k不带参数。
Since getopt
doesn't expect -l to pass an argument, optarg
is set to NULL, which you then subsequently assign to lieferung
. 由于getopt
不希望-l传递参数,因此optarg
设置为NULL,然后将其分配给lieferung
。 You then dereference that variable, resulting in the segfault. 然后,您取消引用该变量,从而导致段错误。
Git rid of the spaces in the format string: 除去格式字符串中的空格:
while ((ch = getopt(argc, argv, "l:k")) != EOF){
I think the format is incorrect. 我认为格式不正确。 Replace "l : k" with "l:k". 将“ l:k”替换为“ l:k”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.