结构体学习笔记



掌叔
2008-06-16 08:56:29

摘自:[url]http://blog.chinaunix.net/u1/52089/showart_467535.html[/url]

以前学习结构体的时候写下来的,hoho怀念一下

一般的程序编写步骤。
1,定义一个结构体
2,实体化一个结构体变量,全局的,用在各个模块上面。
3,子程序用结构体指针来做。
4,主程序传递结构体指针的地址。
#include
#include
#include
typedef struct student{
int age;
}STU; // 定义结构体
STU student1; // 实体化一个结构体变量
// 传址引用和 传值引用的区别,传址的话,是实实在在的修改传进来的数组或指针对应的数据
void Creat(STU *p) // 子程序,用结构体指针来做
{
p->age=23;
}
int main(void)
{
Creat(&student1); // 传递结构体变量的地址。
printf("AGE is %d
",student1.age);
return 0;
}

(2) 结构体里面的成员是指针变量的时候的访问办法
*student1.age,也就是说看成这样:*(student1.age)结构体成员代替了原来的变量
#include
#include
#include
struct scor{
float math;
float english;
};
typedef struct student{
char *name;
int *age;
}STU;
STU student1;

void CreatStu(STU *p)
{
p->name="Etual no";
}
int main(void)
{
int age=23;
student1.age=&age;
CreatStu(&student1);
printf("AGE is %d
",*student1.age);
return 0;
}
下面尝试,结构体里面包含结构体指针,然后访问指针指向的内容
#include
#include
#include
struct scor{
float math;
float english;
};
typedef struct student{
char *name;
int *age;
struct student *next;
}STU;
STU student1;
STU student2;
void CreatStu(STU *p)
{
p->name="Etual no";
}
int main(void)
{
int age=23;
int age2=22;
STU *p=&student2;

p->next=&student1;
p->name="hikari";
p->age=&age2;
student1.age=&age;
CreatStu(&student1);
printf("AGE is %d
",*p->next->age);
return 0;
}
下面尝试,普通指针变量,指向结构体内部的成员变量
#include
#include
typedef struct student{
char *name;
int age;
}STU;
STU student1;
void CreatStu(STU *p)
{
p->name="Etual";
p->age=23;
}
int main(void)
{
int *age;
CreatStu(&student1);
age=&student1.age;
printf("AGE is %d
",*age);
return 0;
}