[英]Cons function not working
I am currently trying to program a function that will cons a new element onto the top of the list, and push the rest of the list back... can anyone help me with this? 我目前正在尝试编写一个函数,将一个新元素放在列表的顶部,然后推回列表的其余部分......任何人都可以帮我这个吗? My program does not work when I try to compile and run it.
当我尝试编译并运行它时,我的程序不起作用。 It goes on an infinite loop.
它继续无限循环。 Any help?
有帮助吗?
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
/* linked lists of strings */
typedef struct sll sll;
struct sll {
char *s;
sll *next;
};
/* By convention, the empty list is NULL. */
/* sll_cons : (char*, sll*) -> sll* */
/* build new list with given string at the head */
/* note: copy the given string to the list (deep copy) */
sll *sll_cons(char *s, sll *ss) {
while (ss != NULL) {
char* temp;
temp = malloc(sizeof(char)*strlen(ss->s));
temp = ss->s;
ss->s = s;
ss->next = malloc(sizeof(char)*strlen(ss->s));
ss->next->s = temp;
ss->next->next = NULL;
ss = ss->next;
}
return ss;
}
Three things I want to mention here. 我想在这里提三件事。
Point 1. You did not check for the success of malloc()
. 要点1.您没有检查
malloc()
是否成功。 You're dereferencing the returned pointer immediately. 您将立即取消引用返回的指针。 If
malloc()
fails, you'll be facing UB. 如果
malloc()
失败,你将面对UB。 [ ss->next->s
] [
ss->next->s
]
Point 2. inside while loop, after allocating memory to ss->next
, you're putting that to ss
and then checking against not NULL, which will never usually be TRUE for malloc()
success. 点2.在循环内部,在将内存分配给
ss->next
,你将它放到ss
然后检查not NULL,对于malloc()
成功,它通常永远不会为TRUE。
Point 3. temp = ss->s;
点3.
temp = ss->s;
no, that's not the way you perform a deep copy . 不,那不是你执行深层复制的方式 。 You have to use
strcpy()
. 你必须使用
strcpy()
。 Otherwise, there's no point allocating memory to temp
. 否则,没有必要为
temp
分配内存。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.