int age;
};
void main() {
struct Man m1 = {“Jack”,30};
//结构体指针
struct Man *p = &m1;
printf("%s,%d\n", m1.name, m1.age);
printf("%s,%d\n",(*p).name,(*p).age);
//“->” 是“(*p)”简写形式
printf("%s,%d\n", p->name,p->age);
system(“pause”);
}
//指针与结构体数组
struct Man
{
char name[20];
int age;
};
void main() {
struct Man mans[] = { {“Jack”,20},{“Rose”,15} };
//遍历叔数组
//1.
struct Man *p = mans;
for (; p < mans +2; p++)
{
printf("%s,%d\n", p->name, p->age);
}
//2.
int i = 0;
printf("%d\n",sizeof(mans));
for (; i < sizeof(mans)/sizeof(struct Man); i++)
{
printf("%s,%d\n", mans[i].name, mans[i].age);
}
system(“pause”);
}
//结构体的大小(字节对齐)
struct Man
{
int age;//4字节
double weight;//8字节
};
void main() {
//结构体变量的大小,必须是最宽基本数据类型的整数倍
//提升读取的效率
struct Man m1 = { 20,89.0 };
printf("%#x,%d\n", &m1, sizeof(m1));//16字节
getchar();
}
//结构体与动态内存分配
struct Man
{
char *name;
int age;
};
void main() {
struct Man m_p = (struct Man)malloc(sizeof(struct Man)*10);
struct Man *p = m_p;
//赋值
p->name = “Jack”;
p->age = 20;
p++;
p-
name = “Rose”;
p->age = 20;
struct Man *loop_p= m_p;
for (; loop_p < m_p + 2; loop_p++)
{
printf("%s,%d\n", loop_p->name, loop_p->age);
}
free(m_p);
getchar();
}
//typedef 类型取别名
//1.不同的名称代表在干不同的事情 typedef int jint
//2.不同的情况下,使用不同的别名
//#if defined(__cplusplus)
//typedef _JNIEnv JNIEnv;
//typedef _JavaVM JavaVM;
struct Man
{
char name[20];
int age;
};
//3.书写简洁
typedef int Age;//将int类型取一个别名类型Age
typedef int* Ap;//将int*类型取一个别名类型Ap
typedef struct Man JavaMan;
typedef struct Man* JM;
//结构体取别名(简写)
typedef struct Woman {
char name[20];
int age;
}W,*WP;//W 是Woman结构体的别名,WP是Woman结构体指针的别名
//typedef struct Woman W;
//typedef struct Woman* WP;
void main() {
int i = 9;
Ap p = &i;
W w1 = { “Rose”,18 };
WP wp1 = &w1;
printf("%s,%d\n", w1.name, w1.age);
printf("%s,%d\n", wp1->name, wp1->age);
getchar();
}
//结构体函数指针成员
typedef struct Girl {
char* name;
int age;
//函数返回值类型,函数指针的名称,函数的参数列表
void(sayHi)(char);
}Girl;
//Girl结构体类似于Java中的类,name和age类似于属性,sayHi类似于方法
typedef Girl* GirlP;
void sayHi(char* text) {
MessageBoxA(0, text, “hello”,0);
}
//改名
void rename1(GirlP gp1) {
gp1->name = “Lily”;
}
void main() {
Girl g1 = { “Xiao” ,18 ,sayHi };
GirlP gp1 = &g1;
//g1.name = “Xiao”;
//g1.age = 18;
//g1.sayHi = sayHi;
g1.sayHi(“Xiaoguo”);
gp1->sayHi(“再见”);
printf("%s,%d\n", gp1->name, gp1->age);
rename1(gp1);
printf("%s,%d\n", gp1->name, gp1->age);
getchar();
}
- 图一
p1 = &g1;
//g1.name = “Xiao”;
//g1.age = 18;
//g1.sayHi = sayHi;
g1.sayHi(“Xiaoguo”);
gp1->sayHi(“再见”);
printf("%s,%d\n", gp1->name, gp1->age);
rename1(gp1);
printf("%s,%d\n", gp1->name, gp1->age);
getchar();
}
- 图一