我刚开始接触C语言。 我像这样设置了一个链表:
#include <stdio.h>
#include <memory.h>
#include <stdlib.h>
#define len(array) (sizeof(array) / sizeof(array[0]))
#define true 1
#define false 0
struct node{
int data;
struct node* next;
};
typedef struct node node;
node* initNode(void){
node* headNode;
headNode = (node *)malloc(sizeof(node));
headNode -> next = NULL;
return headNode;
}
node* create(int* array, int length){
node* newNode;
node* lastNode;
node* headNode = initNode();
newNode = (node *)malloc(sizeof(node));
headNode -> data = array[0];
int arrayLength = 1;
int hasSetHead = false;
while(arrayLength < length){
if (! hasSetHead){
lastNode = headNode;
hasSetHead = true;
}
memset(newNode, 0, sizeof(node));
newNode -> data = array[arrayLength];
newNode -> next = NULL;
lastNode -> next = newNode;
lastNode = newNode;
newNode = (node *)malloc(sizeof(node));
if (newNode == NULL) exit(0);
arrayLength++;
}
return headNode;
}
void clear(node* headNode){
node* nextNode;
if (headNode == NULL) return;
while (headNode -> next != NULL){
nextNode = headNode -> next;
free(headNode);
headNode = nextNode;
}
*headNode = NULL;
}
int main(void){
int array[] = {1,2,3,4,5,6,7};
int length = len(array);
node* list = create(array, length);
clear(list);
system("pause");
return true;
}
我希望通过使用clear(结构体指针)来清除我的结构体。但是在clear()的最后一行,我得到了这个错误:
error: incompatible types in assignment
我应该做什么呢?谢谢!请忘记我的糟糕英语。
谢谢!@Marievi 我已经像这样更改了代码:
headNode = NULL;
但是当我想要打印链表时,它似乎出现了问题。以下是我的代码:
void clear(node* headNode){
node* nextNode;
if (headNode == NULL) return;
while (headNode -> next != NULL){
nextNode = headNode -> next;
free(headNode);
headNode = nextNode;
}
*headNode = NULL;
}
当我调用这个函数时,似乎出现了内存泄漏。