From 44bfe9afa1615f901170d04971665504589b67a1 Mon Sep 17 00:00:00 2001 From: juan Date: Fri, 10 Dec 2021 23:51:00 +0800 Subject: [PATCH] Fix implementation of 2-4 and 2-3 --- semester1/pset13/2-3-ArrayEX.c | 30 ++++++++------------ semester1/pset13/2-4-ArrayEX.c | 51 +++++++++++++++++++++++++++++++++- 2 files changed, 62 insertions(+), 19 deletions(-) mode change 120000 => 100644 semester1/pset13/2-4-ArrayEX.c diff --git a/semester1/pset13/2-3-ArrayEX.c b/semester1/pset13/2-3-ArrayEX.c index 58baa96..3750b5d 100644 --- a/semester1/pset13/2-3-ArrayEX.c +++ b/semester1/pset13/2-3-ArrayEX.c @@ -1,38 +1,33 @@ #include -#include #include #define MAX 100001 void sort(char **arr, int n); -void swap(char **arr1, char **arr2); int main(void) { + char str[MAX]; int n; scanf("%d", &n); + char *arr[n]; getchar(); - // 2d array - char **str = malloc(sizeof(char *) * n); - // Buffer array - char *buffer = malloc(sizeof(char) * MAX); + // Get input + char ch; + int loc = 0; for (int i = 0; i < n; i++) { - fgets(buffer, MAX, stdin); - str[i] = malloc(strlen(buffer) + 1); - strcpy(str[i], buffer); + arr[i] = &str[loc]; + while ((ch = getc(stdin)) != '\n') { + str[loc++] = ch; + } + str[loc++] = '\0'; } - sort(str, n); + sort(arr, n); for (int i = 0; i < n; i++) { - printf("%s", str[i]); + printf("%s\n", arr[i]); } - // Free up memory - free(buffer); - for (int i = 0; i < n; i++) { - free(str[i]); - } - free(str); return 0; } @@ -40,7 +35,6 @@ 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; diff --git a/semester1/pset13/2-4-ArrayEX.c b/semester1/pset13/2-4-ArrayEX.c deleted file mode 120000 index 6104f4b..0000000 --- a/semester1/pset13/2-4-ArrayEX.c +++ /dev/null @@ -1 +0,0 @@ -2-3-ArrayEX.c \ No newline at end of file diff --git a/semester1/pset13/2-4-ArrayEX.c b/semester1/pset13/2-4-ArrayEX.c new file mode 100644 index 0000000..caf5238 --- /dev/null +++ b/semester1/pset13/2-4-ArrayEX.c @@ -0,0 +1,50 @@ +#include +#include +#include +#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; + } + } + } +}