C语言结构体用法详解

来源:互联网 发布:淘宝摄影兼职 编辑:程序博客网 时间:2024/05/20 20:02

以下代码有结构体的各种定义方法,不再详细说明。

直接看代码:

////  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;//定义的时候直接申请变量people2typedef 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] 42015-11-03 09:26:07.299 02-test-c-结构体[692:10375] 82015-11-03 09:26:07.300 02-test-c-结构体[692:10375] people1-322015-11-03 09:26:07.300 02-test-c-结构体[692:10375] people2-242015-11-03 09:26:07.300 02-test-c-结构体[692:10375] people3-242015-11-03 09:26:07.300 02-test-c-结构体[692:10375] dog1-162015-11-03 09:26:07.300 02-test-c-结构体[692:10375] cat1-24Program ended with exit code: 0

由输出可以看出,结构体在内存中是以八个字节为一个单元,如一个short不够八个字节,但也是占用八个字节,所以在定义结构体的时候,需要注意各个变量的顺序,尽可能的少占用内存,当然如果你不在乎内存,那就不必考虑了

0 0
原创粉丝点击