使用传递的字符串创建列表节点

时间:2015-07-28 21:29:33

标签: c structure

List * List_createNode(const char * str)
  {
List * dup = NULL;
// dup = strdup(str);//figure this out

if (dup == NULL)
    {
      fprintf(stderr, "\nString Duplication  Fail 1\n");
      exit(EXIT_FAILURE);
    }   

  dup -> str = strdup(str);
  dup -> next = NULL; // we can also do zero

  return dup;  
}

我正在尝试使用传递的字符串str创建一个新的列表节点。 而不是malloc我需要使用strdup来获取我所做的字符串,如下所示。 结构List有2个属性str和next。

这就是我所拥有的。我哪里错了?

2 个答案:

答案 0 :(得分:0)

咦?

List * dup = NULL;
if (dup == NULL)
{
    fprintf(stderr, "\nString Duplication  Fail 1\n");

是的,dupNULL

尝试:

List * dup = malloc(sizeof(List));
if (dup == NULL)

答案 1 :(得分:0)

strdup只能用于字符串。要创建List节点,这是一种封装字符串的类型,您必须使用malloc

我猜你不允许使用malloc来复制字符串(否则就没有意义了)

所以你需要做的是用

替换那个注释的代码行(想象出来)
dup = malloc(sizeof(List));