一個指針函數的問題

看到一個某公司的面試題目如下:

char *getStr1(void) 
{
	static char str[] = "hello world!";
	return str;
}

char *getStr2(void)
{
	char *str = "hello world!";
	return str;
}
問如果調用這兩個函數進行賦值的話,輸出的值分別爲什麼?

如果不仔細想的話,回答是輸入的結果一樣:hello world!

然而非也,實驗證明以上的答案是錯的

函數getStr1返回值爲輸出的亂碼,函數getStr2爲hello world.


說明如下:
"Hello world"作爲靜態字符串實際上存儲在數據區,但寫程序的人不知道這個地址,而程序本身知道。當某一函數以
{ char p[] = "Hello world"; ...}
方式使用此靜態字符串時,實際上相當於:
  char p[12];
  strcpy(p, "Hello world");
  ....
p[12]是在棧裏臨時分配的。雖然p指向的內容是"Hello world", 但是這是複製品,不是原件。當函數結束,char p[]就被程序回收了,所以p[]的內容就不再是"Hello world"了。
但如果以char *p="Hello world"的方式使用,p指向的是靜態字符串存儲的位置,也就是說指向"Hello world"的原件,當然沒有問題了。

如果想堅持用char p[]而不使用char *p, 有效方法必須是:
{
static char p[]="Hello world";
return p;
}
原因我想很清楚了。static char []是靜態的,存儲在數據區。


以上就涉及到了函數指針,在實現的編程當中也會經常使用的,如下

如果需要實現一個字符串的反轉函數,就可以用以下的代碼來實現

/*
*function: 實現對一個字符串的反轉 
*/
char *strRevse(char *value)
{
	int len = 0;
	char *src = value;
	char *dest = NULL;
	char *pSrc = NULL;
	char *pDest = NULL;

	if (NULL == value)
	{
		return NULL;	
	}
	else
	{
		len = strlen(value);
	}
	dest = (char *)malloc(len);
	pDest = dest;
	pSrc = src+len-1;
	
	while(*pSrc != 0)
	{
		*pDest++ = *pSrc--;
	}
	
	return dest;
}
測試函數
int main(void)
{
	char *src = "abcdefg";

	char *pValue = NULL;
	
	pValue = strRevse(src);
	printf("the value is :%s\n", pValue);
	free(pValue);
        return 0;
}
發佈了30 篇原創文章 · 獲贊 12 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章