C语言中的指针灵活强大,但是要掌握好却相当不易。特别是再配合malloc()函数进行动态内存管理时,很多细节的问题往往较难察觉。本文通过一个例子来探讨C语言中,发生空指针传递时可能会出现的问题。
在下面这个程序中,我们在main()函数里声明一个结构体类型的指针,然后我们在一个函数test()里对它分配内存以及初始化。注意我们省略了动态内存的回收语句free,在实际编程中应该加上这部分。
struct node{
int data;
struct node *next;
};
void test(struct node * head){
head=(struct node *)malloc(sizeof(struct node));
head->data = 1;
head->next = NULL;
}
int main(int argc, const char * argv[]) {
struct node * head = NULL;
test(head);
if(head == NULL)
printf("Fail to allocate m