发送标志-h或-H时,为什么会出现分段错误。
bool parse_command(int argc, char **argv, bool *header, char **fileName)
{
if (!argv)
return false;
bool *flagh = false;
bool *flagH = false;
char *options = "Hh";
int opt = 0;
while ( (opt = getopt(argc, argv, options ) ) != -1)
{
printf("HELLO");
switch (opt)
{
case 'h':
*flagh = true;
break;
case 'H':
*flagH = true;
break;
default:
usage_p1();
return false;
}
}
printf("%d", opt);
// Implement this function
return true;
}
答案 0 :(得分:6)
这两行是你的问题:
bool *flagh = false;
bool *flagH = false;
您将flagh
和flagH
声明为指针为布尔值,但它们并未指向任何位置。事实上,由于你的初始化等同于
bool *flagh = NULL;
bool *flagH = NULL;
你可能不希望这些成为指针。将声明更改为
bool flagh = false;
bool flagH = false;
将作业更改为
flagh = true;
flagH = true;
答案 1 :(得分:2)
看看这个:
bool *flagh = false;
bool *flagH = false;
两个变量都是指针,用false
初始化它们。没有
C中的true
或false
代替了false
评估为0,如果不是true
,则会将其视为false
。
如果这是真正的C代码,那么它与执行
相同bool *flagh = NULL;
bool *flagH = NULL;
稍后你做
*flagh = true;
取消引用NULL
指针,该指针未定义并将导致a
段错误。
修复您的代码:
#include <stdbool.h>
bool flagh = false;
bool flagH = false;
然后迟到
flagh = true;
flagH = true;
// or
flagh = false;
flagH = false;
与许多评论中所说的一样,C没有真正的布尔类型。请参阅:Using boolean values in C
修改
现在有stdbool.h
声明了bool
和true
类型,
false
,但所有工作都是将true
重新定义为1,将false
重新定义为0:
#ifndef _STDBOOL_H #define _STDBOOL_H #ifndef __cplusplus #define bool _Bool #define true 1 #define false 0 #else /* __cplusplus */ /* Supporting _Bool in C++ is a GCC extension. */ #define _Bool bool #if __cplusplus < 201103L /* Defining these macros in C++98 is a GCC extension. */ #define bool bool #define false false #define true true #endif #endif /* __cplusplus */ /* Signal that all the definitions are present. */ #define __bool_true_false_are_defined 1 #endif /* stdbool.h */