【发布时间】: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 = &h;和p = malloc(sizeof(int)); *p = h;之一 -
这里根本不需要使用带有
p的指针。只需将其声明为int p;并分配p = h。