c語言 參數傳值和傳地址


static void TestCharP(char **p)
{
	char *q = "ssssss";
	*p=q;
}

static void TestCharP1(char *p)
{
	char *q = "ssssss";
	p=q;
}

static void TestInt(int *a)
{
	*a = 5;
}

static void TestInt1(int a)
{
	a = 5;
}

static void TestBuf(char buf[])
{
	buf[0] = 'a';
}


//傳值和傳地址的區別
int main()
{
	int a = 0;
	int a1 = 0;
	char *p=NULL;
	char buf[5] = {0};
	char *p1 = NULL;

	TestInt(&a);
	printf("%d\n",a);

	TestInt1(a1);
	printf("%d\n",a1);

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

	TestCharP1(p1);
	printf("%s\n",p1);

	TestBuf(buf);
	printf("%s\n",buf);

	return 0;
}

輸出:

 

2.查看地址轉換

static void TestCharP(char *p)
{
	//p指向地址:0x00045860
	char *q = "ssssss";
	//q指向地址:0x00045858
	p=q;
	//p指向地址:0x00045858
}


//傳值和傳地址的區別
int main()
{
	char *p="aaa";
	//p指向地址:0x00045860
	TestCharP(p);
	//p指向地址:0x00045860
	printf("%s\n",p);

	return 0;
}

查看 p指向地址沒有改變

static void TestCharP(char **p)
{
	//*p指向地址:0x0014f888
	char *q = "ssssss";
	//q指向地址:0x01185858
	*p=q;
	//*p指向地址:0x01185858
}


//傳值和傳地址的區別
int main()
{
	char *p="aaa";
	//p指向地址:0x01185860
	TestCharP(&p);
	//p指向地址:0x00045858
	printf("%s\n",p);

	return 0;
}

  查看 p指向地址改變

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM