C 求字符数组最大值与次大值

来源:互联网 发布:nginx cookie 跨域 编辑:程序博客网 时间:2024/05/16 10:23

实现代码:

#include<stdio.h>#include<stdlib.h>#include<string.h>#define MAXSIZE 100void find_max(char*arr[], int size, char *max, char *second_max){    int i;    for ( i = 0; i < size; i++)    {        if (strcmp(max, arr[i]) <= 0)        {            strcpy(second_max, max);            strcpy(max, arr[i]);        }        if (strcmp(second_max, arr[i]) < 0 && strcmp(max, arr[i]) > 0)        {            strcpy(second_max, arr[i]);        }    }}void main(){    char *arr[MAXSIZE];    char *max = NULL;    char *second_max = NULL;    int str_size;    int i;    max = (char*)malloc(sizeof(char)*MAXSIZE);    second_max = (char*)malloc(sizeof(char)*MAXSIZE);    max[0] = '\0';    second_max[0] = '\0';    printf("input string size:\n");    scanf("%d", &str_size);    printf("input %d strings:\n", str_size);    for (i = 0; i < str_size; i++)    {        arr[i] = (char*)malloc(sizeof(char)*MAXSIZE);        fflush(stdin);//清除数据刚进来时缓冲区数据,防止被gets        gets(arr[i]);    }    find_max(arr, str_size, max, second_max);    printf("max = %s, second_max = %s\n", max, second_max);    system("pause");}

这里写图片描述

0 0