我试图创建一个分配的输入文本文件中的单向链表。我试图做一点点在一个时间,所以我知道我的代码是不完整的。我试图创建的头指针和刚打印出它的价值,我甚至不能得到那个工作,但我不知道为什么。我包括结构,我创建列表,并打印列表功能。我不包括打开的文件,因为这部分工作。

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的第二行应

LIST *root = NULL;

另外,进一步向下有分配显然对于该项目的细节,但a)所述代码失败捕获分配,并保存它的任意位置,以及b)在分配的大小应该是strSize,不的长度变量本身。有几种方法来解决它,但是最直接的将会是:

newList->str = (char *)malloc(strSize);
if (newList->str == NULL)

其他提示

在第二malloc的分配存储器,但它的返回值不被分配给任何东西,以使得所分配的存储器丢失。

newList被分配但尚未初始化,所以使用的memcpy来拷贝存储到newList->海峡将失败,因为newList-> STR分不了了之。可能需要的第二个的malloc的结果被分配给newList-> STR,但忘了。

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

编辑:

LIST *current = head;
while (current != NULL) {
    printf("%s    %d", current->str, current->count);
    current = current->next;
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top