2023-03-31-结构体指针传入函数的问题
错误示范,打印不出L->data的值,因为传入的是指针变量,更改数据的话,要把地址传进函数,才能把更改后的数据传出来:
//单链表
#include <stdio.h>
#include <stdbool.h>
#include <malloc.h>
typedef struct LNode
{
int data;
struct LNode *next;
}LNode,*LinkList;//相当于typedef struct LNode *LinkList; LinkList a相当于struct LNode a
bool initlist(LinkList L)//初始化单链表
{
L->data=0;//赋为空表
return true;
}
int main()
{
LinkList L;//L即头指针
//printf("%d \n",L->data);
initlist(L);
printf("%d \n",L->data);
return 0;
}
正确示范,将指针的地址传入到函数中,即指向指针地址的一个指针,然后解引用,用malloc给头指针分配内存地址
#include <stdio.h>
#include <stdbool.h>
#include <malloc.h>
typedef struct LNode
{
int data;
struct LNode *next;
}LNode,*LinkList;//相当于typedef struct LNode *LinkList; LinkList a相当于struct LNode a
bool initlist(LinkList *L)//初始化单链表
{
(*L)=(LinkList)malloc(sizeof(LinkList));
(*L)->data=0;//赋为空表
return true;
}
int main()
{
LinkList L;//L即头指针
//printf("%d \n",L->data);
initlist(&L);
printf("%d \n",L->data);
return 0;
}