[英]Cons function not working
我目前正在嘗試編寫一個函數,將一個新元素放在列表的頂部,然后推回列表的其余部分......任何人都可以幫我這個嗎? 當我嘗試編譯並運行它時,我的程序不起作用。 它繼續無限循環。 有幫助嗎?
#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;
}
我想在這里提三件事。
要點1.您沒有檢查malloc()
是否成功。 您將立即取消引用返回的指針。 如果malloc()
失敗,你將面對UB。 [ ss->next->s
]
點2.在循環內部,在將內存分配給ss->next
,你將它放到ss
然后檢查not NULL,對於malloc()
成功,它通常永遠不會為TRUE。
點3. temp = ss->s;
不,那不是你執行深層復制的方式 。 你必須使用strcpy()
。 否則,沒有必要為temp
分配內存。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.