新用戶堆棧交換在這裏,所以我道歉,如果我問這個問題不正確。如何排序指向char的指針數組
我有一個任務來創建一個程序,用於將用戶輸入的文本行分配給使用動態內存分配的字符指針數組。
一旦輸入了所有的行,行就會被打印回來。然後通過將第5行和第6行移動到末尾以及向前(「向上」)中間的行來操縱它們。最後,這些行必須按字母順序排序。我的問題在於:我無法獲得一個排序函數來處理一個char指針數組。
我的代碼張貼如下。我不確定我的排序函數是否正確地引用了char指針。我也不確定我的變量是否正確,並且我無法確定是否正確地將char字符串分配給char指針數組中的char指針。你能幫我解決這些問題嗎?
非常感謝, r4mulus
//Program to collect lines of text, shift them in various ways and sort them, and output all the lines at each stage
// Declare libraries
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
// Declaring macros
#define len1 80
// Prototpying functions
void sortLine(char **, int size);
void swap(char **, char **);
// Main body of program
int main (void){
char *line_array[40];
char *(*ptr_all) = &line_array[0];
char buffer[80];
int ch;
int counter = 0;
// Loop to intake lines of text
do {
// Ask user to input a line of text
printf("Please input a line of text to store into memory. Enter '#' to stop collecting lines:\n");
fgets(buffer, len1+1, stdin);
// Check to make sure char '#' has not been entered
ch = buffer[0];
if (ch == '#'){
break;
}
// Measure the length of the line of text
unsigned long len = strlen(buffer);
// Allocate memory for the given line of text
line_array[counter] = (char *)malloc(len+1);
// Copy string in buffer into pointer to array of strings
strcpy(line_array[counter], buffer);
// Clear the buffer
for (int p = 0; p < (len1+1); p++){
buffer[p] = '\0';
}
// Increment the counter
counter++;
} while (counter < 40);
printf("\n");
// Print the lines collected so far
for (int q = 0; q < counter; q++){
printf("%s", line_array[q]);
}
printf("\n");
// Move lines of text 5 and 6 to the end; Move all other following lines forward two line spaces
char *temp_ptr1;
char *temp_ptr2;
temp_ptr1 = line_array[4];
temp_ptr2 = line_array[5];
for (int r = 4; r < counter; r++){
line_array[r] = line_array[r+2];
}
line_array[counter-2] = temp_ptr1;
line_array[counter-1] = temp_ptr2;
// Print the rearranged lines
for (int s = 0; s < counter; s++){
printf("%s", line_array[s]);
}
printf("\n");
// Sort the lines alphabetically
sortLine(ptr_all, counter);
// Print the lines sorted alphabetically
for (int t = 0; t < counter; t++){
printf("%s", line_array[t]);
}
printf("\n\n");
// End the program
return 0;
}
功能
// Function to sort elements in an array
void sortLine(char **a, int size){
int i, j, compare;
for (i = 0; i < size; i++){
for (j = i; j < size; j++){
compare = strcasecmp((a[i]), (a[j]));
if (compare > 0)
swap(&a[i], &a[j]);
}
}
}
// Function to swap elements in an array
void swap(char **a, char **b){
char *temp = *a;
*a = *b;
*b = temp;
}
您提供了太多的代碼。請提供一個簡短的示例程序,最低要求。 – Dai
我在排序函數的任何地方都看不到'strcmp()'。另外,一般來說,你可以使用'buffer'而不是'&buffer [0]' –
@WeatherVane是否必須與'strcmp()?'相比較?我想我可以通過引用提取第一個字符,但我不知道如何。我們應該儘可能少地使用這些庫函數。 – r4mulus