6

我正在尝试从分配的输入文本文件创建一个单链表。我试着一次做一点,所以我知道我的代码不完整。我尝试创建头指针并打印出它的值,但我什至无法让它工作,但我不知道为什么。我包括了结构、我的创建列表和打印列表函数。我没有包含打开的文件,因为该部分有效。

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. */
}
4

3 回答 3

2

root有一个未定义的值,所以它不会初始化。第二行CreateList应该是

LIST *root = NULL;

此外,更下方显然是针对项目细节的分配,但是a)代码无法捕获分配并将其保存在任何地方,并且b)分配的大小应该是strSize,而不是变量本身的长度。有几种方法可以解决它,但最直接的方法是:

newList->str = (char *)malloc(strSize);
if (newList->str == NULL)
于 2010-02-22T07:16:50.290 回答
1

你不应该head = head->next在 for 循环之后增加 head 。PrintList 每次都会返回 NULL,因为循环不会停止,直到 head 为 NULL。为什么你需要返回你刚刚传递给函数的列表的头部呢?

编辑:

LIST *current = head;
while (current != NULL) {
    printf("%s    %d", current->str, current->count);
    current = current->next;
}
于 2010-02-22T07:18:54.630 回答
1

第二个 malloc 分配内存但它的返回值没有分配给任何东西,因此分配的内存丢失了。

newList 已分配但未初始化,因此使用 memcpy 将内存复制到 newList->str 将失败,因为 newList->str 指向任何内容。可能您希望将第二个 malloc 的结果分配给 newList->str,但您忘记了。

于 2010-02-22T07:40:23.783 回答