关于malloc函数的使用

关于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;
}

这样写也是可以的,直接访问结构体内的内容

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值