【问题标题】:Trying to insert a node instead getting repeated values尝试插入节点而不是获取重复值
【发布时间】:2015-04-02 17:51:55
【问题描述】:

我正在尝试将节点添加到链表的开头。程序要求用户输入他想输入的名字的数量,所以如果我输入 3,它应该要求我输入 3 个不同的名字并将它们显示在一个列表中,而不是程序重复打印相同的名字。

    struct node{

      char data[20];
      struct node* link;

    }Damn;


    struct node* head;

    //Insert
    void Insert(char p[20]){

      struct node* temp = (struct node*) malloc(sizeof(struct node));
      strncpy(Damn.data, p);
      temp->link = head;
      head = temp;
    }

   //Print
    void Print()
    {
      struct node* temp = head;
      while(temp != NULL){
        printf(" %s \n", Damn.data );
        temp = temp->link;
      }
    }


    //Main
    int main(){

      head = NULL;

      int i, n;
      char p[20];

      printf("How many names you want to enter\n");
      scanf("%d", &n);

      for(i=1; i<(n+1); i++){
        printf("Enter the %dth  name", i);
        scanf("%s", p);
        Insert(p);
        Print();
      }

【问题讨论】:

    标签: data-structures struct linked-list nodes


    【解决方案1】:

    temp-&gt;data 代替Damn.data。此外,strncpy() 接受三个参数。您应该添加要复制的最大字符数作为第三个参数。

    【讨论】:

    • 嘿,谢谢!在我用 temp->data 替换 Damn.data 后它起作用了。另外,我使用 strcpy 而不是 strncpy(),所以它现在工作正常。但是,我想问一下为什么它不能与 Damn.data 一起工作,这对我来说似乎是合法的。有什么想法吗?
    • 由于你没有typedef你的 Damn 结构定义,它也是一小块未初始化的全局范围内存。但是您的新节点是 malloc 给您的一段堆内存,并且位于 temp 指针中。您的原始代码试图将新字符串复制到那个无用的全局范围内存块中,而不是正确的堆分配块内存。如果你对 Damn 结构定义进行了 typedef,那么编译器会在 strncpy 语句上抛出一个错误,你就会知道那行是错误的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多