用指针数组处理上一题目,字符串不等长

用指针数组处理上一题目,字符串不等长。

解题思路: 与数字的比较没什么区别,只不过需要采用strcmp进行字符串的大小比较,使用指针实现需要在最早接收数据的时候就采用字符串指针数组,这样的好处在于指针的指向可以直接通过赋值进行改变,而指针数组中的字符串的顺序只需要交换不同字符串的地址就可以实现

答案:

#include<stdio.h>
#include<string.h>
void sort(char *s[10])
{
	int i, j;
	for (i = 0; i < 10; i++){
		for (j = i; j < 10; j++){
			if (strcmp(s[i], s[j])> 0){
				char *tmp = s[i]; //指针的好处在于直接通过赋值可以改变指向
				s[i] = s[j];  //只要交换了字符串的地址就实现了字符串的交换
				s[j] = tmp;//因此通过指针指向的交换就能够实现数组中字符串的排序
			}
		}
	}
}
int main()
{
	char *str[10];
	printf("Please enter ten strings:
");
	for (int i = 0; i < 10; i++) {
		str[i] = malloc(32);//为每一个指针分配空间
		scanf_s("%s", str[i], 32);
	}
	sort(str);
	printf("
");
	for (int i = 0; i < 10; i++){
		printf("%s
", str[i]);
        free(str[i]);
	}
	system("pause");
	return 0;
}

用指针数组处理上一题目,字符串不等长

原文地址:https://www.cnblogs.com/weiyidedaan/p/13292843.html