【问题标题】:Segmentation Fault in C(core dumped)--simple pointer [closed]C中的分段错误(核心转储)-简单指针[关闭]
【发布时间】:2013-05-26 11:32:44
【问题描述】:

这里请参考代码中的注释。Segmentation Fault(core dumped) 发生在 *p=h 行中。但是当我在另一个新的 c 文件中单独运行这一行时,它完全没问题

#include<stdio.h>
int *max(int *a,int *b)
{
    if(*a>*b)
    {
        return a;
    }
    else
    {
        return b;
    }
}

int main()
{
    int h=1;
    int *p;
    int i=1,j=2,k=3;
    int *a,*b,*c,*d;

    c=max(&i,&j);
    d=&i;

    printf("\nOutput from the max function %d\n",*c);
    printf("\n%d\n",*d);

    *p=h;  // Line where segmentation fault is occurring

    printf("\n%d\n",*p);

    return 0;
}

【问题讨论】:

  • p 未初始化。
  • 它应该是p = &amp;h;p = malloc(sizeof(int)); *p = h;之一
  • 这里根本不需要使用带有p 的指针。只需将其声明为int p; 并分配p = h

标签: c pointers


【解决方案1】:

指针p 未初始化。它不指向任何存储。

在这里,您尝试取消引用 p 并存储来自 h 的值:

*p = h;

但是p 没有指向任何有效的存储来保存该值。

【讨论】:

  • 此外,c=max(&amp;i,&amp;j); 行是错误的,因为max 返回intcint*
  • 没有最大函数返回int*
  • 哼,对,我看错了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-05-04
  • 2015-05-12
  • 2013-04-28
  • 1970-01-01
  • 2023-04-04
  • 2012-11-20
  • 1970-01-01
相关资源
最近更新 更多