本文介绍了从函数返回指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想从一个函数返回指针。但我正在逐渐分段错误。有人告诉什么是错与code
#包括LT&;&stdio.h中GT;
INT *乐趣();
主要()
{
INT * PTR;
PTR =乐趣();
的printf(%d个,* PTR);}
INT *乐趣()
{
INT *点;
*点= 12;
返回点;
}
解决方案
使用指针之前分配内存。如果你不分配内存 *点= 12
是未定义的行为。
为int *乐趣()
{
为int *点=的malloc(sizeof的*点); / *必须填写。 * /
*点= 12;
返回点;
}
此外,您的的printf
是错误的。您需要取消引用( *
)的指针。
的printf(%d个,* PTR);
^
I am trying to return pointer from a function. But I am getting segmentation fault. Someone please tell what is wrong with the code
#include<stdio.h>
int *fun();
main()
{
int *ptr;
ptr=fun();
printf("%d",*ptr);
}
int *fun()
{
int *point;
*point=12;
return point;
}
解决方案
Allocate memory before using the pointer. If you don't allocate memory *point = 12
is undefined behavior.
int *fun()
{
int *point = malloc(sizeof *point); /* Mandatory. */
*point=12;
return point;
}
Also your printf
is wrong. You need to dereference (*
) the pointer.
printf("%d", *ptr);
^
这篇关于从函数返回指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!