指针作为函数的返回值

#include <stdio.h>
#define A 0
int funcA(int a, int b)
{
	return a + b;
}
int  *funcB(int a, int b)
{
	static int c=A;
	c = a + b;
	return &c;
}
int main(int argc, char **argv)
{
	int *p_int, temp;
	p_int = (funcB(2, 5));
	printf("%d\n", *p_int);
	//第二种不推荐
	temp = *funcB(4, 8);
	/*错误写法 &temp=funcB(5,7);*/
	system("pause");
	return 0;
}

规范写法:

funcB函数为指针函数,返回值为地址。

然后令指针p_int接受返回值。此时c的地址已经存在指针p_int中,之后通过加*号,将p_init 中地址所指的数据输出。
int *p_int;

p_int=*(funcB(2,5));

/*错误写法 &temp=funcB(5,7);*/

错误原因:再声明temp时,该变量的地址已经被操作系统固定,

发布了29 篇原创文章 · 获赞 3 · 访问量 3175

猜你喜欢

转载自blog.csdn.net/qq_38436175/article/details/104042368