Android_NDK C结构体和枚举
结构体定义和使用
struct Worker{
char name[10];
int age;
double salary;
};
//不初始化,有默认值
struct Worker1{
char name[10];
int age;
double salary;
}jack = {"jack",18,200},darry;
struct Name{
char fisrtName[10];
char name[10];
}
struct Worker2{
//可以声明内部类
Name name;
int age;
double salary;
};
void main(){
//不初始化,没有默认值
struct Worker worker = {"awewe",18,1000};
char * name = worker.name;
int age = worker.age;
double salary = worker.salary;
}
结构体指针和动态内存开辟
不推荐
struct Worker{
char name[10];
int age;
double salary;
};
void main(){
//不初始化,没有默认值
struct Worker worker = {"awewe",18,1000};
Worker * wp = &worker;
wp->age = 22;
}
推荐
struct Worker{
char name[10];
int age;
double salary;
};
void main(){
Worker * worker = (Worker *)malloc(sizeof(Worker));
worker-> age = 90;
if(worker){
free(worker);
}
}
结构体数组
struct Worker{
char name[10];
int age;
double salary;
};
void main(){
Worker worker[2] = {{"123",12,123},{}};
Worker * wp = (Worker*) malloc(sizeof(Worker)*3);
//对第一个操作
strcpy(wp->name,"31231");
wp->age = 12;
wp += 1;
//对第二个操作
strcpy(wp->name,"31231");
wp->age = 12;
}
字节对齐和结构体大小计算
计算规则
- 按照最大的字节去计算
- 按照基本数据类型来
- 首先会把所有的加起来,是否能整除最大字节数,不够则累加,一直加到可以整除为止
- 结构体嵌套按照把第一个成员看成结构体中最大的成员
struct Worker{
char name[10];
int age;
double salary;
//10 + 4 +8 = 22
//3 * 8 = 24
//可以整除,则是24
};
struct Worker1{
char name[18];
int age;
double salary;
//18 + 4 +8 = 30
//3 * 8 = 24
//不可以可以整除,则是24 + 8 = 32
};
struct Birth{
int y;
int m;
int d;
//4 + 4 +4 = 12
//可以整除,则是12
};
struct Worker{
int num;
char sex;
int age;
char name[10];
double salary;
struct Birth b;
//4 + 1 +4 + 10 + 12 = 32
//3 * 12 = 36
//可以整除,则是36
};
结构体别名
struct Birth{
int y;
int m;
int d;
};
//取别名
typedef Worker Worker_;
//取别名
typedef Worker * Worker_p;
void main(){
Worker_ worker = {"123",23,23};
Worker_p p = (Worker*)malloc(sizeof(Worker));
}
- 使用typedef可以取多个别名。
- 也可以对结构体指针取别名。
- 也可以不加struct关键字。
联合体
union Person{
char name[10];
int age;
//大小12
}
void main(){
Person p;
//只能拿到age
strcpy(p.name , "DDDDD");
p.age = 12;
//只能拿到name
p.age = 12;
strcpy(p.name , "DDDDD");
}
联合体只能存在一个,要么是name,要么是age。所以构造方法也只能穿一个值。 大小计算就是最大值。被最大值整除即可
枚举
enum ContentType{
TEXT,IMAGE,VOICE
}
void main(){
ContentType ct = TEXT;
ContentType ct1 = VOICE;
//enum类似int
}
|