指针元素的使用

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

程序

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."和空字符串。

相关推荐
wuweijianlove1 小时前
算法性能的渐近与非渐近行为对比的技术4
算法
_dindong1 小时前
cf1091div2 C.Grid Covering(数论)
c++·算法
AI成长日志1 小时前
【Agentic RL】1.1 什么是Agentic RL:从传统RL到智能体学习
人工智能·学习·算法
黎阳之光2 小时前
黎阳之光:视频孪生领跑者,铸就中国数字科技全球竞争力
大数据·人工智能·算法·安全·数字孪生
skywalker_112 小时前
力扣hot100-3(最长连续序列),4(移动零)
数据结构·算法·leetcode
6Hzlia2 小时前
【Hot 100 刷题计划】 LeetCode 17. 电话号码的字母组合 | C++ 回溯算法经典模板
c++·算法·leetcode
wfbcg2 小时前
每日算法练习:LeetCode 209. 长度最小的子数组 ✅
算法·leetcode·职场和发展
_日拱一卒3 小时前
LeetCode:除了自身以外数组的乘积
数据结构·算法·leetcode
计算机安禾3 小时前
【数据结构与算法】第36篇:排序大总结:稳定性、时间复杂度与适用场景
c语言·数据结构·c++·算法·链表·线性回归·visual studio
SatVision炼金士3 小时前
合成孔径雷达干涉测量(InSAR)沉降监测算法体系
算法