利用指针数组进行字符串排序

概念:
一个数组的元素均是指针,则该数组称为指针数组。

使用指针数组处理字符串非常适合。由于字符串长度不定,使用二维字符数组处理会大量浪费存储空间。

代码示例:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

int main()
{
    
    
	int i,j,len;
	char *temp;
	char *str[5];

	printf("请输入5个字符串:\n");
	temp=(char *)malloc(80);
	for(i=0;i<5;i++)
	{
    
    
		fgets(temp,80,stdin);
		fflush(stdin);
		len=strlen(temp);
		if(temp[len-1]=='\n')
		{
    
    
			temp[len-1]='\0';
			len--;
		}
		len++;
		str[i]=(char*)malloc(sizeof(char)*len);
		strcpy(str[i],temp);
	}
	free(temp);
	for(i=0;i<5;i++)
	{
    
    
		for(j=0;j<5-i-1;j++)
		{
    
    
			if(strcmp(str[j],str[j+1])>0)
			{
    
    
				temp=str[j];
				str[j]=str[j+1];
				str[j+1]=temp;
			}
		}
	}
	printf("排序后输出结果:\n");
	for(i=0;i<5;i++)
	{
    
    
		printf("%s\n",str[i]);
	}
	for(i=0;i<5;i++)
	{
    
    
		free(str[i]);
	}
	return 0;
}

与利用二维数组不同,指针数组是将地址值修改而二维数组是将内存数据修改。

猜你喜欢

转载自blog.csdn.net/yooppa/article/details/113753915