gpt4 book ai didi

c - 如何在链表插入函数中插入字符串

转载 作者:行者123 更新时间:2023-11-30 15:35:55 25 4
gpt4 key购买 nike

我想在名为 insert 的函数中将字符串插入到 struct data_node 中。我的struct data_node

struct data_node {
char name [25];
int data;
struct data_node *next;
};

我的插入函数是:

struct data_node * insert (struct data_node **p_first, int elem, char *word ) {

struct data_node *new_node, *prev, *current;
current=*p_first;
while (current != NULL && elem > current->data) {
prev=current;
current=current->next;
} /* end while */

/* current now points to position *before* which we need to insert */
new_node = (struct data_node *) malloc(sizeof(struct data_node));
new_node->data=elem;
new_node->name=*word;

new_node->next=current;
if ( current == *p_first ) /* insert before 1st element */
*p_first=new_node;
else /* now insert before current */
prev->next=new_node;
/* end if current == *p_first */
return new_node;
};

当我编译时,它说,当从类型“char”分配给类型“char[25]”时,第 22 行不兼容类型意味着 new_node->name=*word; 是错误的。我该如何解决这个问题?

最佳答案

链表结构无关。这个问题归结为将一个 char[] 复制到另一个。这将起作用:

strncpy(new_node->name, word, 25);

有一些警告。如果 word 未指向有效的 char[],则可能会导致未定义的行为。如果它指向一个包含 more more than 25 25 个或更多(非空)字符的数组,该操作会将前 25 个复制到 new_node->name 中,这意味着new_node->name不会以空终止,如果其他代码假设它是空终止,则可能会在以后造成麻烦。 正如 WhozCraig 指出的,用 null 终止目标字符串几乎总是一个好主意 - 在确保通过复制比您能复制的字符少一个字符(即 25-1)为其留出空间之后。 您可能会考虑定义一个常量NAMELENGTH,这样您的代码中就不会出现神奇的数字 25。

关于c - 如何在链表插入函数中插入字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22751874/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com