欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C/C++指针数组的实现(代码教程)

程序员文章站 2022-06-17 19:58:35
1)实例申请一个3维的指针数组,数组里再给指针分配内存: #include #include #include typedef struct tagmsg { intbfl...

1)实例申请一个3维的指针数组,数组里再给指针分配内存:

#include 
#include 
#include 

typedef struct tagmsg
{
	intbflag;
	char  *pmsg;
}st_msg;

int main()
{

	st_msg *pstdev = new st_msg [3];
	
	st_msg *pdev = &pstdev[0];
	pdev->pmsg = new char[32];
	sprintf(pdev->pmsg,"%s", "000000000000000000");
	
	pdev = &pstdev[1];
	pdev->pmsg = new char[32];
	sprintf(pdev->pmsg,"%s", "111111111111111111");
	
	st_msg *pdev0 = &pstdev[0];
	st_msg *pdev1 = &pstdev[1];
	
	printf("p0:%s \r\n", pdev0->pmsg);
	printf("p1:%s \r\n", pdev1->pmsg);
	
	delete pstdev[0].pmsg;
	delete pstdev[1].pmsg;
	delete pstdev;
		
 return 0;
}

运行结果:

C/C++指针数组的实现(代码教程)

2)简单实例:

#include 
#include 
#include 


int main()
{
	char *a[3];
	a[0] = new char[32];
	a[1] = new char[32];
	a[2] = new char[32];
	
	char *p;
	p = a[0];
	
	printf("p:%s \r\n", p);
	sprintf(a[0],"%s", "55555555555");
	printf("p:%s \r\n", p);
	
 return 0;
}

运行结果:

C/C++指针数组的实现(代码教程)