新手一枚,然后Debug了一晚上跪了...然后来求助了,谢谢各位
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#define BUF_LEN 100 // Length of input buffer
#define INI_COUNT 5 // Initial count number of strings
void swap(char *a, char *b);
void recursion(char **pstr, int start, int end);
void quick_sort(char **pstr, int len);
int main(void)
{
size_t str_len = 0, // Current string length
str_count = 0, // Current count number of strings
capacity = INI_COUNT; // Current capacity of strings
char buf[BUF_LEN]; // Input Buffer
char* ptr = NULL; // Pointer to check whether fgets works or not
char** pString = (char**)calloc(capacity, sizeof(char*)); // Pointer to strings
//Instruction
printf("Enter strings to be sorted, one per line.\nPress Enter to end input.\n\n");
// Read strings
while(true)
{
ptr = fgets(buf, BUF_LEN, stdin); // Read the string
if(!ptr) // Read error check
{
printf("Error reading string!\n");
free(pString); // Free memory
pString = NULL;
return 1;
}
if(*ptr == '\n') // End read loop check by entering Enter
break;
if(str_count == capacity) // Capacity check
{
capacity++; // Increase capacity by one
pString = (char**)realloc(pString, capacity); // Reallocate memory
if(!pString) // Reallocate memory error check
{
printf("Error reallocating memory!\n");
free(pString); // Free memory
pString = NULL;
return 2;
}
}
str_len = strnlen_s(buf, BUF_LEN) + 1;
// Current string length of pstr and add one for '/0'
pString[str_count] = (char*)malloc(str_len);
// Allocate memory for each string
if(!pString[str_count]) // Read error check
{
printf("Error allocating memory!\n");
size_t i = 0;
for(;i < str_count; i++) // Free memory
{
free(pString[i]);
pString[i] = NULL;
}
free(pString);
pString = NULL;
return 3;
}
strcpy_s(pString[str_count], str_len, buf); // Copy string from buffer
str_count++;
}
// Sort strings
int len = (int)str_count;
quick_sort(pString, len);
// Print strings & free memory
size_t i = 0;
for(; i < str_count; i++)
{
printf("%s\n", pString[i]);
free(pString[i]);
pString[i] = NULL;
}
free(pString);
pString = NULL;
return 0;
}
void swap(char *a, char *b)
{
char *temp = a;
a = b;
b = temp;
}
void recursion(char **pstr, int start, int end)
{
if(start >= end)
return;
int left = start,
right = end - 1,
cmp = 0;
while(left < right)
{
cmp = strcmp(pstr[left], pstr[end]);
while(cmp < 0 && left < right)
{
left++;
cmp = strcmp(pstr[left], pstr[end]);
}
cmp = strcmp(pstr[right], pstr[end]);
while(cmp >= 0 && left < right)
{
right--;
cmp = strcmp(pstr[right], pstr[end]);
}
swap(pstr[left], pstr[right]);
}
cmp = strcmp(pstr[left], pstr[end]);
if(cmp >= 0)
swap(pstr[left], pstr[end]);
else
left++;
if (left)
{
recursion(pstr, start, left - 1);
recursion(pstr, left + 1, end);
}
else
recursion(pstr, left + 1, end);
}
void quick_sort(char **pstr, int len)
{
recursion(pstr, 0, len - 1);
}