Cでの単独リンクリストを作成
-
22-09-2019 - |
質問
私は割り当てのための入力テキストファイルから単独でリンクリストを作成しようとしています。私は私のコードは完全ではありません知っているので、私は一度それを少しやろうとしています。私は、先頭ポインタを作成し、ちょうどその値をプリントアウトしようと、私も仕事にそれを得ることはできませんが、私は確かに理由はありませんよ。私はリストを作成し、リスト機能を印刷する私の、構造体が含まれています。その部分が動作するので、私は開いているファイルが含まれていませんでした。
typedef struct List
{
struct List *next; /* pointer to the next list node */
char *str; /* pointer to the string represented */
int count; /* # of occurrences of this string */
} LIST;
LIST *CreateList(FILE *fp)
{
char input[LINE_LEN];
LIST *root; /* contains root of list */
size_t strSize;
LIST *newList; /* used to allocate new list members */
while (fscanf(fp, BUFFMT"s", input) != EOF) {
strSize = strlen(input) + 1;
/* create root node if no current root node */
if (root == NULL) {
if ((newList = (LIST *)malloc(sizeof(LIST))) == NULL) {
printf("Out of memory...");
exit(EXIT_FAILURE);
}
if ((char *)malloc(sizeof(strSize)) == NULL) {
printf("Not enough memory for %s", input);
exit(EXIT_FAILURE);
}
memcpy(newList->str, input, strSize); /*copy string */
newList->count = START_COUNT;
newList->next = NULL;
root = newList;
}
}
return root;
}
/* Prints sinly linked list and returns head pointer */
LIST *PrintList(const LIST *head)
{
int count;
for (count = 1; head != NULL; head = head->next, head++) {
printf("%s %d", head->str, head->count);
}
return head; /* does this actually return the start of head ptr, b/c I want to
return the start of the head ptr. */
}
解決
root
は、未定義の値を持ちます。 CreateList
の2行目がなければならない
LIST *root = NULL;
また、さらにそこに割り当てが項目の詳細については明らかですが、)コードが割り当てをキャプチャし、任意の場所に保存し、Bに失敗した)割り当てのサイズはstrSize
、ないの長さでなければなりません変数そのもの。そこにそれを修正するには、いくつかの方法がありますが、最も簡単になります:
newList->str = (char *)malloc(strSize);
if (newList->str == NULL)
他のヒント
第二のmalloc割り当てメモリが、その戻り値は、割り当てられたメモリが失われたように、何にも割り当てられていない。
newListは、そのコピーメモリへnewList-> strは何もnewList-> strのポイントので、失敗するとのmemcpyを使用して、割り当てられたが、初期化されていません。おそらく、あなたは第二のmallocの結果はnewList-> STRに割り当てることがしたかったが、あなたはそれを忘れてしまっています。
あなたは、forループでhead = head->next
後に頭をインクリメントするべきではありません。頭がNULLになるまでがprintlistは、ループ文句を言わないの停止以来、NULLを毎回返します。なぜあなたはとにかくあなただけの関数に渡されたリストの先頭を返す必要がありますか?
編集ます:
LIST *current = head;
while (current != NULL) {
printf("%s %d", current->str, current->count);
current = current->next;
}