函數中的*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被銷燬,裏面的元素不存在了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章