C 将单词读入链接列表
我试图写一个程序,读取用户输入的每个单词,然后将该单词粘贴到一个链接列表中。这是我迄今为止尝试过的,但遇到seg故障,但不太确定mallocing/指针哪里出了问题。(尚未实施打印列表)C 将单词读入链接列表,c,struct,linked-list,malloc,nodes,C,Struct,Linked List,Malloc,Nodes,我试图写一个程序,读取用户输入的每个单词,然后将该单词粘贴到一个链接列表中。这是我迄今为止尝试过的,但遇到seg故障,但不太确定mallocing/指针哪里出了问题。(尚未实施打印列表) #包括 #包括 #包括 #定义最大长度20 类型定义结构节点{ 字符*字; 结构节点*下一步; }节点t; 节点读取(节点读取); 作废打印列表(node_t*node); node_t*insertNode(char*word,node_t*node,int size); int main(int argc,
#包括
#包括
#包括
#定义最大长度20
类型定义结构节点{
字符*字;
结构节点*下一步;
}节点t;
节点读取(节点读取);
作废打印列表(node_t*node);
node_t*insertNode(char*word,node_t*node,int size);
int main(int argc,char*argv[]){
node_t*start=NULL;
printf(“输入句子:\n”);
读取(开始);
返回0;
}
无效*读取(节点*node){
int i,大小=最大长度;
字符c,*字;
如果(!(word=malloc(大小))){
printf(“内存不足!\n”);
退出(退出失败);
}
而((c=getchar())!='\n'){
对于(i=0;c!='';i++){
字[i]=c;
如果(i>大小){
尺寸=尺寸*2;
如果(!realloc(字,大小)){
printf(“内存不足\n”);
退出(退出失败);
}
}
}
节点=插入节点(字、节点、大小);
}
返回节点;
}
node_t*insertNode(char*word,node_t*node,int size){
节点\u t*新节点,*当前节点;
new_node=(node_t*)malloc(sizeof(node_t));
新建节点->下一步=空;
如果(!(新建节点->word=malloc(大小))){
printf(“内存不足\n”);
退出(退出失败);
}
strcpy(新节点->单词,单词);
if(node==NULL){
节点=新节点;
当前=新节点;
}
否则{
当前->下一步=新节点;
当前=新节点;
}
返回节点;
}
我认为错误是由线路引起的
return node;
在插入节点中
。那应该是
return new_node;
有几个问题:
- 您的原型与
的实现不匹配;使两者都返回一个read
节点*
- 您有两个嵌套的输入循环,一个从
读取,另一个循环遍历字符。内部循环从未更新其条件,因为stdin
只能由外部循环更改。应该只有一个循环,负责从流中读取和写入字符串c
- 您不保留
的结果,这意味着您不会在分配内存的句柄更改时反映更新。在这些情况下,您将访问已无效的旧句柄realloc
- 字符串不能以空字符结尾
- 在访问超出范围的内存之前,应该重新分配内存。这通常意味着在写入数组之前检查是否放大数组。请注意,对于长度为
的数组,n
本身已经是非法索引n
的结果应该是一个getchar
,而不是一个int
,这样所有有效的输入都不同于char
,您不需要检查它EOF
read
相关的问题。我还没有研究链表插入
为了正确地以零结束字符串,我建议编写一个无限循环,并在可能的重新分配之后推迟中断
条件。例如:
node_t *read(node_t *node)
{
int size = MAX_LEN;
int i = 0;
char *word = malloc(size);
if(word == NULL) {
printf("Out of memory!\n");
exit(EXIT_FAILURE);
}
while (1) {
int c = getchar();
if(i >= size) {
size = size*2;
word = realloc(word, size);
if (word == NULL) {
printf("Out of memory\n");
exit(EXIT_FAILURE);
}
}
if (c == '\n' || c == EOF) {
word[i] = '\0';
break;
}
word[i++] = c;
}
node = insertNode(word, node, size);
return node;
}
node_t *read(node_t *node)
{
int size = MAX_LEN;
int i = 0;
char *word = malloc(size);
if(word == NULL) {
printf("Out of memory!\n");
exit(EXIT_FAILURE);
}
while (1) {
int c = getchar();
if(i >= size) {
size = size*2;
word = realloc(word, size);
if (word == NULL) {
printf("Out of memory\n");
exit(EXIT_FAILURE);
}
}
if (c == '\n' || c == EOF) {
word[i] = '\0';
break;
}
word[i++] = c;
}
node = insertNode(word, node, size);
return node;
}