我一直在独自完成 Kochan 的“Programming in C”第 3 版,为明年的研究生院做准备,但我第一次被困住了。我离指针还有一章,但是最近关于字符串的这一章末尾的练习有一个问题,我自己的研究似乎表明只能通过使用指针来解决。
问题与数据结构有关entry
:
struct entry {
char word[15];
char definition[50];
};
我们创建一个条目数组:
struct entry dictionary[10] =
{{"aardvark", "a burrowing African mammal"},
{"abyss", "a bottomless pit"},
{"addle", "to become confused"},
{"aerie", "a high nest"},
{"ajar", "partially opened"},
{"acumen", "mentally sharp; keen"},
{"affix", "to append; attach"},
{"agar", "a jelly made from seaweed"},
{"ahoy", "a nautical call of greeting"},
{"aigrette", "an ornamental cluster of feathers"}};
提示内容为:“编写一个名为的函数dictionary_sort
,将字典按照[上面]的定义按字母顺序排序。”
我知道与函数有关的结构和数组有一些微妙之处,以及函数如何将它们作为参数或将它们作为返回值返回。对我来说似乎有意义的唯一方法是返回一个结构,或者特别是一个结构数组,但我认为我在这里没有正确应用它:
struct entry dictionary_sort(struct entry dictionary)
总的来说,我当前的程序版本如下:
#include <stdio.h>
#include <stdbool.h>
struct entry {
char word[15];
char definition[50];
};
// Function to compare two character strings
int compare_strings(const char s1[], const char s2[])
{
int i = 0, answer;
while (s1[i] == s2[i] && s1[i] != '\0' && s2[i] != '\0')
i++;
if (s1[i] < s2[i])
answer = -1; // s1 < s2
else if (s1[i] == s2[i])
answer = 0; // s1 == s2
else
answer = 1; // s1 > s2
return answer;
}
// Function to sort a dictionary structure
struct entry dictionary_sort(struct entry dictionary[])
{
int dictionary_length = sizeof(dictionary) / sizeof(dictionary[0]);
int i, j, minimum;
struct entry temp;
for (i = 0; i < dictionary_length; i++) {
minimum = i;
for (j = i + 1; j < dictionary_length; j++) {
if (compare_strings(dictionary[j].word,
dictionary[minimum].definition) == -1)
minimum = j;
}
temp = dictionary[minimum];
dictionary[minimum] = dictionary[i];
dictionary[i] = dictionary[minimum];
}
return dictionary;
}
int main(void)
{
struct entry dictionary[10] =
{{"aardvark", "a burrowing African mammal"},
{"abyss", "a bottomless pit"},
{"addle", "to become confused"},
{"aerie", "a high nest"},
{"ajar", "partially opened"},
{"acumen", "mentally sharp; keen"},
{"affix", "to append; attach"},
{"agar", "a jelly made from seaweed"},
{"ahoy", "a nautical call of greeting"},
{"aigrette", "an ornamental cluster of feathers"}};
int i, dictionary_length = sizeof(dictionary) / sizeof(dictionary[0]);
dictionary = dictionary_sort(dictionary);
for (i = 0; i < dictionary_length; i++)
printf("%s - %s.\n", dictionary[i].word, dictionary[i].definition);
return 0;
}
字符串比较函数的行为与预期一样,因为它只返回一个整数。我真的不知道如何在不了解指针的情况下拥有所需的功能。有足够多的带有指针的示例可供查找,但我很好奇我在这里缺少什么基本原则,因为我觉得书中的其他所有内容对我来说都非常自然。
先感谢您!