קוד לדוגמה
הנה קוד חלקי, אני מקווה שתלמד ממנו משהו, ושהבנתי אותך נכון. הקוד ממומש תחת ההנחה שאין להשתמש ברשימות דינמיות, ולכן הוא גם לא יעיל.
#include <string.h> /* strcmp(), strcpy() or implement those yourself */ #ifndef FALSE #define FALSE 0 #endif #ifndef TRUE #define TRUE 1 #endif #define SizeOfWord 15 #define NumberOfWords 50 typedef char[SizeOfWord] Word; typedef Word[NumberOfWords] Words; /* .....Prototypes here... */ void MakeUpSpace (Words *words, int index) { /* * we will lose the last element by shifting all the elements, * starting with the one at position ´index´, by 1 to the right */ int i; for (i = NumberOfWords - 1; i >= index; i--) { strcpy((*words), (*words)[i - 1]); } } int AddWord(Words *words, Word *word) { int i = 0; int wordFound = FALSE; int currentSizeOfWord = 0; /* The last comparing result */ while (i < NumberOfWords && !wordFound && currentSizeOfWord > 0) { currentSizeOfWord = strcmp(*word, (*words)); if (currentSizeOfWord == 0) /* if words are equal */ wordFound = TRUE; } if (wordFound) { return FALSE; /* word was found, set we cannot add */ } else { /* we found the place to insert */ /* you need to decide what to do in the case (i == NumberOfWords) */ MakeUpSpace(words, i); /* Shift all the words to the right */ strcpy((*words), *word); /* set new word */ } } int main() { Words words; Word word; InitWords(&words); while (UserWantsToAddAWord()) { GetWordFromUser(&word); AddWord(&words, &word); } return 0; }