c - 为什么运行此函数时会出现段错误?

标签 c segmentation-fault flags getopt

为什么当我发送标志 -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;
}

最佳答案

这两行是你的问题:

bool *flagh = false;
bool *flagH = false;

您将 flaghflagH 声明为 bool 值的指针,但它们尚未指向任何地方。事实上,它们绝对没有指向任何地方,因为您的初始化相当于

bool *flagh = NULL;
bool *flagH = NULL;

您可能不希望这些成为指针。将声明更改为

bool flagh = false;
bool flagH = false;

将分配更改为

flagh = true; 

flagH = true; 

关于c - 为什么运行此函数时会出现段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48391216/

相关文章:

`const char*` 会导致问题吗?

c - strtok 的段错误和存储到变量中?

c - 我的代码中的 c 段错误。

go - 如何将 bool 参数传递给标志

Eclipse 设置详细 :class Flag for Launch Configuration

Linux - 网卡的标志配置

c - 曾几何时,> 比 < ... 快,什么?

c - 这种在 C 字符串中访问字符的方式如何工作?

linux - 需要帮助解决 libc-2.23.so 中的段错误

C 2D 字符串数组在其声明的函数之外导致段错误