赞
踩
#include <stdio.h> #include <stdlib.h> #include <string.h> void sort(char (*s)[10], int n); //定义排序函数 int main(){ char n[10][10], (*p)[10]; for(p = n, printf("Please enter 10 strings: "); p < n + 10; scanf("%s", *p++)); //输入10个字符串 sort(n, 10); //调用排序函数 for(p = n, printf("Sort by: "); p < n + 10; printf("%s ", *p++)); //输出10个字符串 printf("\n"); system("pause"); return 0; } //排序函数 void sort(char (*s)[10], int n){ int i, j; char t[10]; for(i = 0; i < n; i++) for(j = i + 1; j < n; strcmp(*(s+i),*(s+j)) > 0 ? strcpy(t, *(s+i)), strcpy(*(s+i), *(s+j)), strcpy(*(s+j), t), j++ : j++); }
#include <stdio.h> #include <stdlib.h> #include <string.h> #define M 3 #define N 80 void initialStr(char ***str, int m, int n){ *str = (char**)malloc(m * sizeof(char*)); for(int i = 0; i < m; i++){ (*str)[i] = (char*)malloc(n * sizeof(char)); } } void inputStr(char **str, int m){ printf("Enter %d strings:\n", m); for(int i = 0; i < m; i++){ printf("Enter No.%d strings: ", i + 1); gets(str[i]); } } void sortStr(char **str, int m, int n){ char *temp = (char*)malloc(n * sizeof(char)); for(char **p = str; p < str + m; p++){ for(char **q = p + 1; q < str + m; q++){ if(strcmp(*p, *q) > 0){ strcpy(temp, *p); strcpy(*p, *q); strcpy(*q, temp); } } } free(temp); } void outputStr(char **str, int m){ printf("\nNew sort:\n"); for(int i = 0; i < m; i++){ printf("%s\n", str[i]); } } void freeStr(char ***str, int m){ for(int i = 0; i < m; i++){ free((*str)[i]); } free(*str); } int main(){ char **str = NULL; initialStr(&str, M, N); inputStr(str, M); sortStr(str, M, N); outputStr(str, M); freeStr(&str, M); system("pause"); return 0; }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。