C语言中,很多时候,使用指针会减少很多代码,使得写出来的代码比较明朗,但是,便捷性也会带来很多的麻烦,一不小心就会增加很多的检查代码的工作量。
我觉得,在使用指针的时候,首先要记得一个原则:初始化
所有指针在使用之前必须要初始化,如:
- char* pfile = NULL;
- int* age = NULL;
- struct Node *pNode = NULL;
下面的代码是有问题:
- #include <stdio.h>
- #include <stdlib.h>
- #define NUM 2
- struct Student
- {
- int age;
- int stu_num;
- char *name;
- char *addr;
- };
- struct Student *stu[NUM] = {NULL};
- int main()
- {
- int i=0;
- int count=1;
- for(i=0;i<NUM;i++)
- {
- stu[i]=(struct Student *)malloc(sizeof(struct Student));
- if(stu[i] == NULL)
- {
- printf("Can't malloc memory for stu[%d]\n",i);
- exit(12);
- }
- printf("The stu[%d] address is %p\n",i,stu[i]);
- printf("Input the %d student information\n",count);
- printf("age: ");
- scanf("%d",&stu[i]->age);
- printf("\nstudent id: ");
- scanf("%d",&stu[i]->stu_num);
- printf("\nstudent name: ");
- scanf("%s",stu[i]->name);
- printf("\nstudent address: ");
- scanf("%s",stu[i]->addr);
- count++;
- }
- while(i<2)
- {
- free(stu[i]);
- i++;
- }
- return 0;
- }
编译上面的代码是没有报错和警告的(FreeBSD 9.0上GCC),但正是因为这样,在运行编译出来的程序会报错,会在哪里报错呢?看下面的截图:
是当输入name的时候,程序就自动退出了,检查程序,发现name是一个结构体的成员,而且是个指针成员,但在程序任何一处地方,没发现有对结构体指针成员初始化的工作,所以,可以判断是由于指针未初始化就使用引起的程序错误,对指针初始化如下:
- stu[i]->name=(char *)malloc(sizeof(char));
最后的完整、正确的代码如下:
- #include <stdio.h>
- #include <stdlib.h>
- #define NUM 2
- struct Student
- {
- int age;
- int stu_num;
- char *name;
- char *addr;
- };
- struct Student *stu[NUM] = {NULL};
- int main()
- {
- int i=0;
- int count=1;
- for(i=0;i<NUM;i++)
- {
- stu[i]=(struct Student *)malloc(sizeof(struct Student));
- stu[i]->name=(char *)malloc(sizeof(char));
- stu[i]->addr=(char *)malloc(sizeof(char));
- if(stu[i] == NULL)
- {
- printf("Can't malloc memory for stu[%d]\n",i);
- exit(12);
- }
- printf("The stu[%d] address is %p\n",i,stu[i]);
- printf("Input the %d student information\n",count);
- printf("age: ");
- scanf("%d",&stu[i]->age);
- printf("\nstudent id: ");
- scanf("%d",&stu[i]->stu_num);
- printf("\nstudent name: ");
- scanf("%s",stu[i]->name);
- printf("\nstudent address: ");
- scanf("%s",stu[i]->addr);
- count++;
- }
- while(i<2)
- {
- free(stu[i]);
- free(stu[i]->name);
- free(stu[i]->addr);
- i++;
- }
- return 0;
- }
到最后,别忘了把你申请的内存。
转载于:https://blog.51cto.com/zoufuxing/985803