如何使此函数采用任意字符串?

所以基本上,现在,这个函数只能用9个单词,每个10个字符。 如何制作它以便它可以采用arbitrary数量的wordscharacters并按字母顺序对其进行相应的排序?

 int sortText(){ char name[10][9], tname[10][9], temp[10]; int i, j, n; printf("Enter the amount of words you want to sort (max 9):"); scanf("%d", &n); printf("Enter %d words: ",n); for (i = 0; i < n; i++) { scanf("%s", name[i]); strcpy(tname[i], name[i]); } for (i = 0; i < n - 1 ; i++){ for (j = i + 1; j  0){ strcpy(temp, name[i]); strcpy(name[i], name[j]); strcpy(name[j], temp); } } } printf("\n------------------------------------------\n"); printf("%-3s %4s %11s\n", "Input","|", "Output"); printf("------------------------------------------\n"); for (i = 0; i < n; i++) { printf("%s\t\t%s\n", tname[i], name[i]); } printf("------------------------------------------\n"); } 

你有两个问题,每个都需要单独解决,但仍然可以用类似的方式解决,即使用动态内存分配,更重要的是重新分配

这里要记住两个重要方面,第一个是字符串是一个字符数组(带有一个特殊的终止字符),并且你可以有一个指向位于内存中任何位置的数组的指针。

如果我们从数据类型开始以及如何存储字符串,你想要的是一个数组数组,就像你现在一样,但是动态分配,这意味着你需要一个指针数组(对于字符串),但是因为字符串数组也需要是动态的,所以你需要一个指向数组的指针,该数组包含指向其他数组的指针,即指向charchar **指针的指针。

现在,当我们知道要使用哪种数据类型时,让我们考虑如何分配它。 要为数组中的单个字符串分配空间,可以使用malloc函数分配一个char *

 char **strings = malloc(1 * sizeof(char *)); 

那是一个简单的部分。 在我们开始阅读实际字符串之前,让我们考虑如何向集合添加新字符串:这是通过使用realloc函数重新分配您拥有的字符串数组来完成的:

 char **temp_strings = realloc(strings, current_count + 1 * sizeof(char *)); if (temp_string == NULL) { // Allocation failed, handle error appropriately } strings = temp_strings; ++current_count; 

这里变量current_count是字符串数组的当前长度,它应该最初初始化为1 (因为我们在数组中只有一个字符串)。

现在读取实际的字符串,这有点复杂,因为我们实际上无法读取整个字符串(因为我们不知道每行是多长时间)。 相反,我们一次读取一个字符,并在我们触及换行符时结束。 我们还需要为每个字符重新分配字符串。

也许是这样的:

 int ch; char *s = NULL; size_t current_length = 0; // Current length of string while ((c = fgetc(stdin)) != EOF) { if (c == '\n') break; // Newline, done with the current string if (s == NULL) { s = malloc(2); // Allocate two character: One for c and one for the terminator } else { // The current length is not including the terminator // that's why we add two characters char *temp_s = realloc(s, current_length + 2); if (temp_s == NULL) { // Handle error } s = temp_s; } s[current_length++] = c; s[current_length] = '\0'; // Terminate as a string } if (s != NULL) { // "Add" the string to the array of strings strings[current_count] = s; } 

对于C,您应该使用位于动态的char指针。 您可以通过实现链接列表来制作列表。 然后strcmp仍然运作良好。 请在此处查看链接列表: http : //www.cprogramming.com/tutorial/c/lesson15.html