排序字符串的一个案例

首先我们必须了解一下两种声明的不同点:

int (*pz)[2]  //pz指向两个包含int类型值的数组(等同于一个指向数组的指针,该数组内含两个int类型值)
int pz[][2]   //另一种写法
int *pax[2]   //pax是一个内含两个指针元素的数组,每个元素都是int的指针
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define SIZE 81
#define LIM 20
void stsrt(char *str[],int );
int main()
{
	int j;
	int i = 0;
	char *find;
	char input[LIM][SIZE];
	char *ptstr[LIM];    /*内含指针变量的数组(数组中储存的是指针变量)*/

	printf("Input up to %d lines,and I will sort them.\n",LIM);
	printf("To stop,press the Enter key at a line's start.\n");

	while (1)
	{
		fgets(input[i], SIZE, stdin);
		if (*(input[i]) == '\n')
			break;
		find = strchr(input[i], '\n');
		if (find)
			*find = '\0';
		ptstr[i] = input[i];    /*指针ptrst[i]指向数组input[i]的首字符*/
		i++;
	}
	stsrt(ptstr, i);
	for (j = 0;j < i+1;j++)
	{
		fputs(ptstr[j],stdout);
		putchar('\n');
	}
}
void stsrt(char *str[LIM], int num)  /*排序函数*/
{
	int j,i;
	char *temp;
	for (i = 0;i < num;i++)
		for (j = 0;j < num;j++)
		{
			if (strcmp(str[j], str[j + 1]) > 0)
			{
				temp = str[j + 1];
				str[j + 1] = str[j];
				str[j] = temp;
			}
		}
}

该程序创建了一个数组,用于储存指针变量。
该程序的巧妙之处在于排序的是指向字符串的指针,而非字符串本身。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值