指针元素的使用

指针作为数组元素指向字符串,指针元素按照指向的字符串由长到短的顺序存放。

程序

cpp 复制代码
#define ARRAY_LEN  5

void bubble_a(char *dat,char n,char *p[]);
void swap1( char *xp, char *yp );
void swap2( char **xp, char **yp );

void main( )
{
	char *myStrPtr[ARRAY_LEN]=
		{
		 "If anything can go wrong,it will.",
		 "Nothing is foolproof.",
         "",
		"hello world.",
		 "Every solution breeds new problem."
		};
	char SLEN[ARRAY_LEN]={0};
	int i,j;
	
	for(i=0; i<ARRAY_LEN; i++)
	  for(j=0; *(myStrPtr[i]+j)!='\0'; j++)
	    SLEN[i] += 1;
	bubble_a(SLEN, ARRAY_LEN, &myStrPtr[0]);
	while(1);
}
	void bubble_a(char *dat,char n,char *p[])
  {
	 int i,next;
	 for(next=1; next<n; next++)
	   for(i=next-1; i>=0; i--)
	    if(dat[i+1]>dat[i])   //条件成立,调用交换函数swap1、swap2
			{
				swap1(&dat[i+1],&dat[i]);
				swap2(&p[i+1],&p[i]);	
			}
   }
	void swap1( char *xp, char *yp )
  {
	 char temp;
	 temp=*xp;
	 *xp=*yp;
	 *yp=temp;
  }
	
  /*  指针xp、yp指向的是地址, *xp是p[i+1],*yp是p[i]  */
  void swap2( char **xp, char **yp )   
  {
	char *temp;
	temp=*xp;
	*xp=*yp;
	*yp=temp;
  }

执行程序后,数组myStrPtr的元素依次指向"Every solution breeds new problem.","If anything can go wrong,it will.", "Nothing is foolproof.","hello world."和空字符串。

相关推荐
lsylalalala1 小时前
常见的排序算法1
数据结构·算法·排序算法
想吃火锅10052 小时前
【leetcode】54. 螺旋矩阵
算法·leetcode·矩阵
想吃火锅10052 小时前
【leetcode】300. 最长递增子序列
算法·leetcode·职场和发展
imaol12 小时前
数据结构---队列
java·数据结构·算法
数模竞赛Paid answer2 小时前
2026年电工杯数学建模A题绿电直连型电氢氨园区优化运行求解全过程论文及程序
算法·数学建模·电工杯
疯狂打码的少年2 小时前
【数据结构】串的模式匹配:KMP算法(重点)
数据结构·笔记·算法
晚风醉蝶3 小时前
第零篇-算法全景图
算法
疯狂打码的少年4 小时前
【数据结构】树的基本概念与二叉树定义
java·数据结构·笔记·算法
webmote334 小时前
用 NVIDIA Nemotron 3 Super + .NET 构建有记忆的多轮对话
后端·算法
Keven_114 小时前
算法札记:区分稀疏图与稠密图在经验上的数学计算差异
算法·稠密图·稀疏图