我有一个创建结构链接列表的函数。
struct words {
char * word;
words next;
};
typedef struct words s_words;
typedef words * Words;
我有一个使用此代码创建链接列表的函数
Words w = NULL; // start of the list
Words t; // temp node
if (t = (Words) malloc(sizeof(s_words))) {
t->word = a_string_created;
t->next = w;
w = t; // Adding at start of the list
}
如果我做了一个printf("%s",t->word)
,printf("%s",a_string_created)
我得到了相同的价值。
我的问题是当我尝试word
从另一个函数中检索时。
int readWords(Words list, char * wordRead) {
if (list != NULL) {
//strcpy(wordRead,list->word);
wordRead = list->word;
return 1;
}
else {
return 0;
}
}
我无法获得readWords
. 它给了我一个printf("%s",list->word)
奇怪的字符。并从调用者函数
char rw[11]; //I've try char* rw too
readWords(aList,rw);
printf("%s",rw)
什么都不打印。
我已经坚持了几个小时了。肯定有一些我看不到/不理解的东西。
编辑:
我通过在我的 printfs 上替换t->word = a_string_created;
为Now 部分解决了我的问题,我打印字符串值。strcpy(t->word, a_string_created);
但是对于某些值,该值略有变化,例如: test 变为 uest !
回答
更改t->word = a_string_created;
为t->word = strdup(a_string_created);
任何人都可以帮助并向我解释我在哪里以及为什么错了?