您的位置:首页 > 编程语言 > C语言/C++

C语言结构体用法详解

2015-11-03 09:37 435 查看
以下代码有结构体的各种定义方法,不再详细说明。

直接看代码:

//
// main.m

#import <Foundation/Foundation.h>

struct{
char * name;
int age;
char * sex;
int test;
}people1;
//定义的时候直接申请结构体变量people1,并且没有结构体名,意味着这个结构体只有在定义结构体的时候申请了一个结构体变量,以后也不能申请结构体变量了
struct{
char * name;
char * sex;
int age;
int test;
}people3;//看似和上面一样,是为了测试结构体内存占用情况,详见输出
struct People{
char * name;
char * sex;
int age;
}people2;//定义的时候直接申请变量people2
typedef struct Dog{//加上typedef 相当于 struct Dog == SubDog,用法如下main里面代码
char * name;
int age;
short test;
}SubDog;
typedef struct{//这里可是和上面Dog一样加上Cat,也可以不写
short test;
char * name;
int age;
}SubCat;

int main(int argc, const char * argv[]) {
@autoreleasepool {
// insert code here...

NSLog(@"%lu", sizeof(int));
NSLog(@"%lu", sizeof(char *));
NSLog(@"people1-%lu", sizeof(people1));
NSLog(@"people2-%lu", sizeof(people2));
NSLog(@"people3-%lu", sizeof(people3));

struct Dog dog1;
SubCat cat1;

NSLog(@"dog1-%lu", sizeof(dog1));
NSLog(@"cat1-%lu", sizeof(cat1));

//people1 people2都是结构体变量,在定义结构体的时候定义的变量,可以直接使用
people1.name = "tom";
people1.age = 20;
people1.sex = "bog";

people2.name = "tom";
people2.age = 20;
people2.sex = "bog";

}
return 0;
}
输出:
2015-11-03 09:26:07.299 02-test-c-结构体[692:10375] 4
2015-11-03 09:26:07.299 02-test-c-结构体[692:10375] 8
2015-11-03 09:26:07.300 02-test-c-结构体[692:10375] people1-32
2015-11-03 09:26:07.300 02-test-c-结构体[692:10375] people2-24
2015-11-03 09:26:07.300 02-test-c-结构体[692:10375] people3-24
2015-11-03 09:26:07.300 02-test-c-结构体[692:10375] dog1-16
2015-11-03 09:26:07.300 02-test-c-结构体[692:10375] cat1-24
Program ended with exit code: 0
由输出可以看出,结构体在内存中是以八个字节为一个单元,如一个short不够八个字节,但也是占用八个字节,所以在定义结构体的时候,需要注意各个变量的顺序,尽可能的少占用内存,当然如果你不在乎内存,那就不必考虑了
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息