#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void merge(char** arr, int left, int mid, int right) {
int i, j, k;
int n1 = mid - left + 1;
int n2 = right - mid;
char** L = (char**)malloc(n1 * sizeof(char*));
char** R = (char**)malloc(n2 * sizeof(char*));
for (i = 0; i < n1; i++)
L[i] = arr[left + i];
for (j = 0; j < n2; j++)
R[j] = arr[mid + 1 + j];
i = 0;
j = 0;
k = left;
while (i < n1 && j < n2) {
if (strlen(L[i]) <= strlen(R[j])) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++;
}
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
free(L);
free(R);
}
void mergeSort(char** arr, int n) {
int currSize, leftStart;
for (currSize = 1; currSize <= n - 1; currSize = 2 * currSize) {
for (leftStart = 0; leftStart < n - 1; leftStart += 2 * currSize) {
int mid = leftStart + currSize - 1;
int rightEnd = (leftStart + 2 * currSize - 1) < (n - 1) ? (leftStart + 2 * currSize - 1) : (n - 1);
merge(arr, leftStart, mid, rightEnd);
}
}
}
int main() {
char inputFileName[100];
char outputFileName[100];
printf("輸入文件名:");
scanf("%s", inputFileName);
printf("輸出文件名:");
scanf("%s", outputFileName);
FILE* inputFile = fopen(inputFileName, "r");
FILE* outputFile = fopen(outputFileName, "w");
if (inputFile == NULL) {
printf("無法打開入文件。\n");
return 1;
}
if (outputFile == NULL) {
printf("無法輸出文件。\n");
return 1;
}
char** strings = NULL;
char buffer[100];
int count = 0;
while (fgets(buffer, sizeof(buffer), inputFile) != NULL) {
buffer[strcspn(buffer, "\n")] = '\0';
strings = (char**)realloc(strings, (count + 1) * sizeof(char*));
strings[count] = (char*)malloc((strlen(buffer) + 1) * sizeof(char));
strcpy(strings[count], buffer);
count++;
}
mergeSort(strings, count);
for (int i = 0; i < count; i++) {
fprintf(outputFile, "%s\n", strings[i]);
}
for (int i = 0; i < count; i++) {
free(strings[i]);
}
free(strings);
fclose(inputFile);
fclose(outputFile);
printf("排序完成。\n");
return 0;
}
想問各位大神為什麼會回報return value 3221225477