1. struct结构体关于不同的定义使用方式,内存分配的方式也是不同的,我使用代码测试一下内存的分配来理解一下。
#include "stdafx.h"
#include <Windows.h>
struct student
{
int id;
char *name; //使用数组,下面给name属性赋值会出现“表达式必须是可修改的左值”
char sex;
int age;
};
int _tmain(int argc, _TCHAR* argv[])
{
struct student test; //对象用.
test.id=001;
test.age=18;
test.name="loong"; //char数组指针 赋值 数组指针变量
test.sex='f';
printf("学生id:%d, 学生年纪:%d, 学生名字:%s, 学生性别:%c, \n",test.id,test.age,test.name,test.sex);
struct student *p; //指针用->
p = (student*)malloc(sizeof(student));
p->id=002;
p->age=22;
p->name="loong"; //char数组指针 赋值 数组指针变量
p->sex='m';
printf("学生id:%d, 学生年纪:%d, 学生名字:%s, 学生性别:%c, ",test.id,test.age,test.name,test.sex);
system("pause");
return 0;
}
定义第1个结构体时, test对象是分配好内存的,你可以直接使用。但第2个是结构体指针,并没有内存的分配,要使用得使用malloc()或calloc()函数分配内存给这个指针。
附加小知识:结构体中数组哪行,表达式必须是可修改的左值
2. typedef 使用的意义
#include "stdafx.h"
#include <Windows.h>
typedef struct student
{
int id;
char *name; //使用数组,下面给name属性赋值会出现“表达式必须是可修改的左值”
char sex;
int age;
}student,*s;
int _tmain(int argc, _TCHAR* argv[])
{
student test; //对象用.
test.id=001;
test.age=18;
test.name="loong"; //char数组指针 赋值 数组指针变量
test.sex='f';
printf("学生id:%d, 学生年纪:%d, 学生名字:%s, 学生性别:%c, \n",test.id,test.age,test.name,test.sex);
student *p; //指针用->
p = (student*)malloc(sizeof(student));
p->id=002;
p->age=22;
p->name="loong"; //char数组指针 赋值 数组指针变量
p->sex='m';
printf("学生id:%d, 学生年纪:%d, 学生名字:%s, 学生性别:%c, ",p->id,p->age,p->name,p->sex);
system("pause");
return 0;
}
其实说简单点,以后定义不在加个struct 这个鬼东西而已,typedef是预定义使用,