多级指针的使用

本文通过一个具体的程序示例介绍了如何使用多级指针,包括二级指针和三级指针,来实现内存的动态分配、打印、交换及释放等功能。通过对这个例子的学习,读者可以更好地理解多级指针的工作原理及其在实际编程中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

对二级指针进行了扩展引出三级指针到多级指针


#include "stdio.h"
#include "string.h"
#include "stdlib.h"
//申请内存
int **getmems18(char ***pw,int num)
{

	char** p2=NULL;
	int i=0;

	if(pw == NULL)
	{
		return -1;
	}
	p2=(char**)malloc(sizeof(char*) * num);

	for(i=0;i<num;i++)
	{
		p2[i] = (char*)malloc(100);
		sprintf(p2[i],"%d%d%d",i+1,i+2,i+3);
	}
	*pw=p2;

	return 0;
}
//打印函数
void prints18(char ***p22,int num)
{
	int i=0;
	char **temp=*p22;

	if(p22 == NULL)
	{
		return;
	}

	for(i=0;i<num;i++)
	{
		printf("%s\n",temp[i]);
	}
}
//交换函数
void swap_p(char*** p22,int num)
{
	int i=0,j=0;
	char buff[100];
	char ** temp = *p22;

	if(p22 == NULL)
	{
		return;
	}

	for(i=0;i<num;i++)
	{
		for(j=i+1;j<num;j++)
		{
			if(  strcmp(temp[i],temp[j]) <0 )
			{
				//交换指针
				/*remp=p2[i];
				p2[i]=p2[j];
				p2[j]=remp;*/
				//交换内存
				strcpy(buff,temp[i]);
				strcpy(temp[i],temp[j]);
				strcpy(temp[j],buff);
			}
		}
	}
}
//释放内存
void freeit18(char ***p2,int num)
{
	int i=0;
	char **temp=NULL;

	temp=*p2;

	for(i=0;i<num;i++)
	{
		if(temp[i]!=NULL)
		{
			free(temp[i]);
			temp[i]=NULL;
		}
	}
	if(temp!=NULL)
		free(temp);

}

void main()
{
	char **p2=NULL;
	int num=10;
	int i=0,j=0;
	int len1=0,len2=0,len3=0;
	char *remp=NULL;	
	char buff[100];
	//申请内存
	getmems18(&p2,num);
	//打印
	printf("start\n");
	prints18(&p2,num);

	swap_p(&p2,num);

//打印
	printf("end\n");
	prints18(&p2,num);
	//释放内存
	freeit18(&p2,num);

	system("pause");
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值