首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在c++中设置链表

在c++中设置链表
EN

Stack Overflow用户
提问于 2014-03-22 00:25:59
回答 4查看 95关注 0票数 0

我正在尝试建立一个链表,但在每个位置都得到相同的元素-

代码语言:javascript
复制
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>

#define LENGTH 45

typedef struct node
{
    char* word;
    struct node* next;
}
node;


int main(void)
{

    node* head = NULL;  //start of list
    // open input file 
    FILE* inptr = fopen("smalllocal", "r");
    if (inptr == NULL)
    {
        printf("Could not open %s.\n", "smalllocal");
        return 2;
    }
    printf("Opened file\n");

    //Get a word from dictionary
    char str1[LENGTH +1];
    while (fscanf(inptr, "%s", str1) != EOF)
    {      
        node* new_node = malloc(sizeof(node));  //malloc space for a new node
        if (new_node == NULL)
        {
            return 3;
        }
        new_node->word = str1;
        // is it the first insertion at this index?
        if (head == NULL)
        {
              new_node->next = head;
              head = new_node;
        }
        else
        // collision so insert at front of list
        {
            new_node->next = head;
            head = new_node;
        }
    }
    fclose(inptr);
    printf("Closed file\n");
    node* pointer = head;
    while (pointer != NULL)
    {
        printf("%s\n", pointer->word);
        pointer = pointer->next;
    }

    return 0;
}

文件'smalllocal‘包含大约15个不同的单词,但末尾的print例程只打印出文件中每个位置的最后一个元素。有人能帮帮忙吗??

EN

Stack Overflow用户

发布于 2014-03-22 00:36:17

你不能简单的做

代码语言:javascript
复制
new_node->word = str1;

您需要首先分配内存,然后将字符串复制到内存中...

代码语言:javascript
复制
new_node -> word = (char *) malloc( sizeof(char)*(LENGTH +1) );
strcpy(new_node -> word, str1);

这应该就行了。否则,链表中的所有指针都指向相同的内存位置。

票数 0
EN
查看全部 4 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22564201

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档