Fix implementation of 2-4 and 2-3

This commit is contained in:
juan 2021-12-10 23:51:00 +08:00
parent 4df6ada921
commit 44bfe9afa1
No known key found for this signature in database
GPG key ID: 5C1E5093C74F1DC7
2 changed files with 62 additions and 19 deletions

View file

@ -1,38 +1,33 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#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;

View file

@ -1 +0,0 @@
2-3-ArrayEX.c

View file

@ -0,0 +1,50 @@
#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;
}
}
}
}