结构体内的指针

利用 结构体对象 对 结构体内的指针 赋值

#include "stdafx.h"
#include <string.h>
#include <stdlib.h>

struct Student
{
	char* name; //从节省空间的角度触发 名字多长,占多少空间
	int score;  //例如 char name[1000] 1000个字节中只用了4个字节就造成了浪费
};


int _tmain(int argc, _TCHAR* argv[])
{
	struct Student stu;  //stu生成在栈上
	stu.score = 100;
	//strcpy(stu.name, "i love you china"); 
	//会挂掉 因为指针name指向区域是未知的

	char buf[100];
	printf("请输入姓名:");
	scanf("%s", buf);
	int len = strlen(buf);

	stu.name = (char*)malloc(len + 1); //为name地址申请相应大小的内存
	strcpy(stu.name, buf); //再进行赋值操作

	printf("%s  %d\n", stu.name, stu.score);
	return 0;
}


利用 结构体类型的指针 对 结构体内的指针 赋值

#include "stdafx.h"
#include <string.h>
#include <stdlib.h>

typedef struct Student
{
	char* name;
	int score;
}Stu;


int _tmain(int argc, _TCHAR* argv[])
{
	Stu *ps = (Stu*)malloc(sizeof(Stu));//在堆上申请结构体类型大小的内存
	ps->score = 100;
	//strcpy(ps->name, "i love you"); 
	//会出错,因为堆中Stu中的指针指向的地址未知
	ps->name = (char*)malloc(100); //为结构体中的指针申请空间
	strcpy(ps->name, "i love you only you");

	printf("name=%s   score=%d\n", ps->name, ps->score);

	free(ps->name); //顺序不能反 需要由内而外的释放
	free(ps);
	return 0;
}


评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值