指针的指针及函数形参

#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

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