大佬教程收集整理的这篇文章主要介绍了尝试从链表中删除最后一个元素并将其保存到作为参数传递的变量中,给出段错误,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个链表,我试图在其中删除 [
{
"database": "book","index": "book","nodes": {
"table": "book","columns": [
"ID","isbn","title","description"
],"transform": {
"mapPing": {
"title": {
"type": "text","copy_to": "full_name"
},"description": {
"type": "text","full_name": {
"type": "text"
}
}
}
}
}
]
的最后一个元素,并将我传递给该函数的参数设置为 char*
。但是,这要么会导致段错误,要么会打印出乱码。为什么会发生这种情况?
这是链表:
char*
这里是它的功能(我很确定其他功能有效,但 remove_last 无效):
struct List_node {
char* name;
struct List_node* next;
};
typedef struct List_node node;
在函数内部,当我打印 int remove_last(node* head,char* ret) {
while(head) {
if (head->next->next == NulL) {
printf("here\n");
ret = strdup(head->next->Name);
printf("%s\n",ret);
printf("there\n");
//free(head->next);
//head->next = NulL;
return 0;
}
head = head->next;
}
return -1;
}
voID add_last(char* name,node* current) {
node* new_node;
new_node = (node*)malloc(sizeof(nodE));
while(current) {
if (current->next == NulL) {
current->next = new_node;
new_node->name = name;
return;
}
current = current->next;
}
}
node* add_first(char* name,node* head) {
node* new_node;
new_node = (node*)malloc(sizeof(nodE));
new_node->name = name;
new_node->next = head;
head = new_node;
return head;
}
时,我得到了我应该得到的结果,但是在我的 main 中,当我尝试打印出传递给参数的 ret
变量时:
ret
我遇到了段错误。我最初认为可能是因为我正在设置节点并释放它们,但我也使用了 strdup(我认为将其复制到新位置或类似的东西?)。我认为这也可能与我如何将 char *temp = NulL;
remove_last(head,temp);
printf("%s\n",temp);
设置为 null 然后我没有在函数中正确设置分配 temp
有关?有什么建议吗?
对于初学者来说,函数 add_last
是不正确的,可以调用未定义的行为。
首先它不检查指针current
(我认为它可以是指向头节点的指针)是否等于NULL
。在这种情况下存在内存泄漏,因为新创建的节点没有附加到列表中。
其次函数没有将新创建的节点的数据成员next
设置为NULL
如果使用您的方法来实现函数add_first
node * add_last(char* name,node *head ) {
node* new_node;
new_node = (node*)malloc(sizeof(nodE));
new_node->name = name;
new_node->next = NULL;
if ( head == NULL )
{
head = new_node;
}
else
{
current = head;
while ( current->next ) current = current->next;
current->next = new_node;
}
return head;
}
对于函数remove_last
那么函数参数ret
是函数的局部变量,退出函数后就不会存活。函数参数的类型必须为 char **。即对应的参数必须通过引用传递给函数。
在任何情况下,该函数都是不正确的,因为它忽略了列表仅包含一个节点的情况。您还需要通过引用将指针传递给头节点。
函数可以如下所示。
int remove_last( node **head,char **ret )
{
int result = *head == NULL ? -1 : 0;
if ( result == 0 )
{
while( ( *head )->next != NULL ) head = &( *head )->next;
*ret = strdup( ( *head )->name );
free( *head );
*head = NULL;
}
return result;
}
以上是大佬教程为你收集整理的尝试从链表中删除最后一个元素并将其保存到作为参数传递的变量中,给出段错误全部内容,希望文章能够帮你解决尝试从链表中删除最后一个元素并将其保存到作为参数传递的变量中,给出段错误所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。