指針的指針及函數形參

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
class A
{
public:
	void getMemory(char **p, char *pStr)
	//等價於void getMemory(char **p, char pStr[]),都是把數組的首地址,即爲指針,傳入進來
	{
		*p = (char *)malloc(100);
		//pStr =const_cast<char*>("welcome to here");//只是改變指針的指向,並沒把值存入原來數組的首地址開始的內存 \
		pStr只是形參,當函數返回後,原來的數組pStr裏面並沒有值

		pStr[0] = 'a';//給數組的首地址存入字符a
		strcpy_s(pStr, 99, "today is today");//數組的首地址存入字符串
	}

	void PutStr(char ** pstr)
	{
		*pstr= const_cast<char*>("welcome to here");//*ptr爲解引用,是給指針的指針pstr的值*pstr賦值, \
		雖然pstr作爲形參,函數PutStr裏面改變pstr的指向是沒有用的,函數調用完就析構了,只有直接改變其值才 \
		能帶出函數
	}

	void test()
	{
		char *str = NULL;
		char pStr[100] = { 0 };
		char *pstr = NULL;
		getMemory(&str, pStr);
		PutStr(&pstr);//指針pstr的地址(也是指針),即指針的指針,作爲參數
		strcpy_s(str, 99,"hello world\n");
		printf(str);
		printf("%s\n",pStr);
		printf(pstr);
	}
};

void main()
{
	A a;
	a.test();
	return;
}

輸出

hello world
today is today
welcome to here

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