【问题标题】:Cons function not working缺点功能不起作用
【发布时间】:2015-02-18 05:28:23
【问题描述】:

我目前正在尝试编写一个函数,该函数将在列表顶部添加一个新元素,并将列表的其余部分推回...有人可以帮我解决这个问题吗?当我尝试编译和运行它时,我的程序不起作用。它进入一个无限循环。 有什么帮助吗?

#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;
}

【问题讨论】:

  • 好吧,ss-&gt;s = s; 看起来很可疑。
  • 我可以不这样做吗?我以为我正在将指针“ss->s”设置为等于指针。 “s”

标签: c list struct infinite-loop cons


【解决方案1】:

我想在这里提到三件事。

第 1 点。 您没有检查 malloc() 是否成功。您正在立即取消引用返回的指针。如果malloc() 失败,你将面临 UB。 [ss-&gt;next-&gt;s]

第 2 点。 在 while 循环中,在将内存分配给 ss-&gt;next 之后,将其放入 ss,然后检查 not NULL,这对于 @987654327 通常永远不会为 TRUE @成功。

第 3 点。 temp = ss-&gt;s; 不,这不是您执行深层复制的方式。你必须使用strcpy()。否则,分配内存给temp 是没有意义的。

【讨论】:

  • 为了避免这种情况,我应该在“while”语句中添加一个“if”子句吗?
  • @LeehoLim 我没有看你的代码逻辑,但是是的,你应该总是检查malloc()的返回值是否为NOT NULL,然后再使用返回的指针。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-05-29
  • 2017-11-14
  • 2017-01-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多