【问题标题】:Pre increment operator and dereference operator resulting in segmentation fault, can't seem to understand why预增量运算符和取消引用运算符导致分段错误,似乎无法理解为什么
【发布时间】:2021-04-28 04:35:01
【问题描述】:

在要求计算输出的测试中找到以下代码。

#include <stdio.h>

int gate(char *P)
{
    char *q = P;
    q++;
    *q++;
    ++*q;
    return(q-P);
}


int main()
{
    char *s = "gateexam";
    int x = gate(s);
    printf("%d",x);
}

在在线编译器上运行它,但由于“++*q”行(注释掉该行使程序运行良好),由于某种原因导致分段错误。

不明白是什么原因造成的

screenshot of code and output

【问题讨论】:

    标签: pointers segmentation-fault dereference pre-increment


    【解决方案1】:

    不明白是什么原因造成的

    代码中的错误导致了这种情况。这个程序试图修改一个字符串文字,这是语言规则所禁止的。

    你可以这样修复它:

    int main()
    {
        char s[] = "gateexam";
    ...
    

    【讨论】:

      猜你喜欢
      • 2010-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-08
      • 1970-01-01
      • 2012-04-25
      相关资源
      最近更新 更多