嗨,伙计们,我在学C编程。我想写一些代码学习链表的主题,但有一个问题。这段代码是关于创建带有5个节点的链表,向第3个节点写入一些内容,并将它们打印到控制台。
以下是我所有的代码:

#include <stdio.h>
#include <stdlib.h>
#include <memory.h>

struct node{
     char *data;
     struct node *next;
};

typedef struct node node;
node *root;


void nodeAdd(node *n, int x)
{
  node *iter;
  iter=root;

  for(int i=0;i<x;i++)
  {
    iter->next = (node*)malloc(sizeof(node));
    iter->next->data="0";
    iter->next->next=NULL;

    iter=iter->next;
    printf("Node created.\n");
  }
}

void nodeWrite(node *n,char *string,int x)
{
  node *temp;
  temp=root;

  for(int k=0;k<x;k++)
  {
    temp=temp->next;
  }
  strcpy(temp->data,string);  //HERE IS ERROR
  printf("\n");
  printf("%s \n",temp->data);
  printf("Node writed.");
}

void nodePrint(node *n)
{
  while(root->next!=NULL)
    printf("%s\n",root->data);
  root=root->next;
}

int main(int argc, const char * argv[])
{
  root = (node*)malloc(sizeof(node));

  nodeAdd(root,5);
  nodeWrite(root,"WTF", 3);
  nodePrint(root);

  return 0;
}

最佳答案

data是未初始化的指针变量。使用分配的有效内存的地址初始化。这将解决问题。现在你的行为被罚款了。
你能做的就是
使用char array而不是指针。
动态分配内存。
如果是1。

struct node{

     char data[MAXSTRINGLEN];
     struct node *next;
};

如果是2:
最初使指针指向NULL。所以现在你可以这样分配
temp->data = malloc(sizeof *temp->data*MAXSTRINGLEN);
if( temp->data == NULL)
{
    fprintf(stderr,"Error in malloc");
    exit(1);
}

只有一点,当你完成工作时释放分配的内存。
这里不需要使用全局变量。您始终可以从内存中传递返回指针并将其分配给struct node*。或者可以使用双指针。这里不需要使用全局变量。
清除多余且不需要的代码。这使得事情可读性和不那么混乱。

08-04 15:30