c - 多函数调用期间指向当前节点的节点指针

标签 c pointers linked-list

我已经声明了一个全局指针 ptr 并希望它在不同的函数调用期间指向当前节点。

这是一个示例代码,我在 fun1 中创建一个新节点并插入到链接列表中。在 func2 中,我想用不同的值更新 linklist 中 newNode 的其他成员。

当前我正在遍历链接列表以获取我不想要的当前节点或最后一个节点,因为在插入新记录期间我们已经必须遍历以到达最后一个节点,从而存储最后一个节点的地址。

但是通过执行以下操作,我没有获得正确的值。请有人指出我哪里出错了。

我正在这样做:

#include<stdio.h>
#include <stdlib.h>
struct Node
{
    int data1;
    int data2;
    struct Node* next;
};
struct Node* head=NULL;
struct Node* ptr =NULL;                    /* Global pointer  */
void insertNode(struct Node ** , struct Node* );
void fun1();
void fun2();


void fun1()
{  
    struct Node* ptr1 =NULL;
    ptr1 = (struct Node*)malloc(sizeof(struct Node*));
    ptr1->data1=1; /* intilaizing with some values */
    insertNode(&head,ptr1);
}

void fun2()
{
    /* Updating the current Node in the linklist with new value . */ 
    ptr->data2=2;

}

void insertNode(struct Node ** head, struct Node* NewRec)
{

if(*head ==NULL ) 
{
    NewRec->next = *head;
   *head = NewRec;
    ptr=*head;
}
else
{
/* Locate the node before the point of insertion */
    struct Node* current=NULL;
    current = *head;
    while (current->next!=NULL )
    {
        current = current->next;
    }
    NewRec->next = current->next;
    current->next = NewRec;
    ptr=current->next;

    }
}
int main ()
{
    fun1();
    fun2();
    while(head!=NULL)
    {
        printf("%d", head->data1);
        printf("%d",head->data2);
        head=head->next;
    }
    return 0;

}

最佳答案

你犯了一个典型的错误。

这是错误的:

ptr1 = (struct Node*)malloc(sizeof(struct Node*));

这里分配的空间是sizeof(struct Node*),它是指针的大小(通常是4或8字节,具体取决于平台)。但是你需要为整个struct Node结构分配空间,其大小为sizeof(struct Node)

所以你只需要这个:

ptr1 = (struct Node*)malloc(sizeof(struct Node));

顺便说一句:在 C 中,你不会转换 malloc 的返回值,所以你实际上应该这样写:

ptr1 = malloc(sizeof(struct Node));

关于c - 多函数调用期间指向当前节点的节点指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43109318/

相关文章:

c - strcmp错误: passing argument 2 of 'strcmp' makes pointer from integer without a cast [-Wint-conversion]

c - 链表,但是每个 "next"指针都指向下一个节点的 "next"指针

c# - 如何在 C# 中从指向内存流的 int 指针获取数据?

将字符串复制到C中的字符指针

c++ - 链表反转

WNDCLASSEX的概念,良好的编程习惯和系统类的WndProc

c - 如何将 float 转换为fix16_14?

c - 使用 pthread 读取文件并执行操作

c - 添加节点后返回指向链表开头的指针?

c - 删除单链表C中字符串中出现的子串