【问题标题】:Passing a String as a Function in a Linked List in C在 C 的链表中将字符串作为函数传递
【发布时间】:2022-11-26 15:37:05
【问题描述】:

因此,我想创建此代码以在插入之前对链表中的字符串进行排序。我无法在代码中找到错误,但每当我尝试将输入传递给插入函数时,它都会显示“分段错误(核心已转储)”——类似的内容。

我的想法是,为了排序,我会使用 strcmp() 来比较字符串,然后根据值插入。 这是代码,

struct node {
  char name[50];
  struct node *next;
};

struct node *insert(struct node *head, char *name) {
  printf("%s NAME",
         name) // To check if the string is correctly passed. Shows above error.
      struct node *toinsert,*temp;
  toinsert = (struct node *)malloc(sizeof(struct node));
  strcpy(toinsert->name, name);
  temp = head;
  while (temp->next != NULL) {
    int a = strcmp(temp->next->name, toinsert->name);
    if (a > 0) {
      break;
    } else {
      temp = temp->next;
    }
  }
  toinsert->next = temp->next;
  temp->next = toinsert;
  return head;
}

int main() {
  struct node *head = NULL;
  char a[48] = "A";
  head = insert(head, a);

  return 0;
}

【问题讨论】:

  • 我想是的,不是吗?我已将 head 定义为仅节点,并将其作为函数中的指针传递。
  • 当 head 为 NULL 时,您的代码失败。 head 变为 temp 然后立即使用。
  • 缺少标头且第一个 printf() 未以“;”结尾所以这是一个语法错误

标签: c sorting data-structures linked-list singly-linked-list


【解决方案1】:

正如@HymnsForDisco 所说,您需要处理 head 为空的情况。添加了缺失的标头并修复了 printf() 处的语法错误:

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

struct node {
    char name[50];
    struct node *next;
};

struct node *insert(struct node *head, const char *name) {
    printf("%s NAME
", name);
    struct node *toinsert = malloc(sizeof(struct node));
    strcpy(toinsert->name, name);
    if(!head) {
        return toinsert;
    }

    struct node *temp = head;
    while (temp->next != NULL) {
        int a = strcmp(temp->next->name, toinsert->name);
        if (a > 0) {
            break;
        } else {
            temp = temp->next;
        }
    }
    toinsert->next = temp->next;
    temp->next = toinsert;
    return head;
}

int main() {
    struct node *head = insert(NULL, (const char *) {"A"});
}

【讨论】:

    猜你喜欢
    • 2015-01-02
    • 2012-11-15
    • 1970-01-01
    • 1970-01-01
    • 2010-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多