指针元素的使用

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

程序

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

相关推荐
晊晌_h6 小时前
嵌入式从0到精通——数据结构总结[特殊字符]
数据结构·算法·排序算法
我找到地球的支点啦6 小时前
Matlab系列(009) 一CRC循环冗余校验详解
开发语言·数据结构·算法·matlab·信息与通信
罗西的思考6 小时前
【OpenClaw具身硬件】ZeroClaw 源码阅读笔记(3)--- RAG
人工智能·算法·机器学习
浪里镖客7 小时前
位姿转换矩阵写法-个人习惯(计算机理解其实是相反的)
线性代数·算法·矩阵
小白羊丨10 小时前
如何诊断 Prompt 模板导致的效果下降?
人工智能·算法·prompt
OPEN-F11 小时前
C++11/14新特性精讲:移动语义与智能指针实战
开发语言·c++·算法
lisin-lee-cooper12 小时前
【leetcode658】有序数组找出k个最接近x的数
java·数据结构·算法
sunburn-12 小时前
Java堆(Heap)详解与实战教学
java·开发语言·数据结构·ide·算法
智碳能碳管理平台12 小时前
工业能耗台账标准化:能碳管理系统的数据口径怎么设计
算法·能碳管理系统·智碳能碳管理平台·企业能碳管理系统·碳排放核算软件·绿色工厂申报saas·能碳管理平台
带多刺的玫瑰13 小时前
Leecode#15刷题之三数之和
算法·leetcode·职场和发展