BUPT-homework/semester1/pset13/2-4-ArrayEX.c

51 lines
947 B
C
Raw Normal View History

2021-12-10 23:51:00 +08:00
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 1001
void sort(char **arr, int n);
void swap(char **arr1, char **arr2);
int main(void) {
int n;
scanf("%d", &n);
getchar();
// 2d array
char **str = malloc(sizeof(char *) * n);
// Buffer array
char *buffer = malloc(sizeof(char) * MAX);
for (int i = 0; i < n; i++) {
fgets(buffer, MAX, stdin);
str[i] = malloc(strlen(buffer) + 1);
strcpy(str[i], buffer);
}
sort(str, n);
for (int i = 0; i < n; i++) {
printf("%s", str[i]);
}
// Free up memory
free(buffer);
for (int i = 0; i < n; i++) {
free(str[i]);
}
free(str);
return 0;
}
void sort(char **arr, int n) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n - 1; j++) {
if (strcmp(arr[j], arr[j + 1]) > 0) {
// Why I can't use swap() here?
char *tmp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = tmp;
}
}
}
}