利用 结构体对象 对 结构体内的指针 赋值
#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;
}