我正在尝试建立一个链表,但在每个位置都得到相同的元素-
#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例程只打印出文件中每个位置的最后一个元素。有人能帮帮忙吗??
发布于 2014-03-22 00:36:17
你不能简单的做
new_node->word = str1;您需要首先分配内存,然后将字符串复制到内存中...
new_node -> word = (char *) malloc( sizeof(char)*(LENGTH +1) );
strcpy(new_node -> word, str1);这应该就行了。否则,链表中的所有指针都指向相同的内存位置。
https://stackoverflow.com/questions/22564201
复制相似问题