函数中的*p、p[]的区别

#include <stdio.h>

char *test()
{
	char *p = "hello world";
	return p;
}

int main()
{
	char *p = test();

	printf("%s\n", p);

	return 0;
}

输出:hello world

#include <stdio.h>

char *test()
{
	char p[] = "hello world";
	return p;
}

int main()
{
	char *p = test();

	printf("%s\n", p);

	return 0;
}

输出错误!

区别如果是指针p,则p指向存放字符串常量的地址,返回p则是返回字符串常量地址值,调用函数结束字符串常量不会消失(是常量)。所以返回常量的地址不会出错。

如果是数组p,则函数会将字符串常量的字符逐个复制到p数组里面,返回p则是返回数组p,但是调用函数结束后p被销毁,里面的元素不存在了。

猜你喜欢

转载自blog.csdn.net/hola_ya/article/details/80625729