关于malloc函数的使用
一个指针变量定义之后,他要么指向某个地址,要么就需要给他动态分配一个内存,
否则他就是野指针,而且如果是结构体指针,必须要先动态分配一段内存,否则直
接对结构体中的元素赋值操作是错误的,即使编译没有问题,运行也会出错。
# include <stdio.h>
# include <malloc.h>
# include <string.h>
# include <stdlib.h>
typedef struct student{
char name[20];
int age;
}stu, *pstu;
int main()
{
char name[20];
pstu stu1;
stu1 = (struct student *)malloc(sizeof(struct student)); //动态分配内存
if(NULL == stu1)
{
printf("内存分配失败!");
exit(-1);
}
printf("请输入学生姓名:\n");
scanf("%s", name);
strcpy(stu1->name, name);
printf("年龄:\n");
scanf("%d", &stu1->age);
printf("%s %d\n", stu1->name, stu1->age);
free(stu1);
return 0;
}
这里运行是没有问题的,但是如果不分配内存就会出错
```c
# include <stdio.h>
# include <malloc.h>
# include <string.h>
# include <stdlib.h>
typedef struct student{
char name[20];
int age;
}stu, *pstu;
int main()
{
// char name[20];
pstu stu1;
stu1 = (struct student *)malloc(sizeof(struct student));
printf("请输入学生姓名:\n");
scanf("%s", stu1->name);
// strcpy(stu1->name, name);
printf("年龄:\n");
scanf("%d", &stu1->age);
printf("%s %d\n", stu1->name, stu1->age);
free(stu1);
return 0;
}
这样写也是可以的,直接访问结构体内的内容