结构体与char型的转换

来源:互联网 发布:电视剧源码 编辑:程序博客网 时间:2024/06/06 08:56

转载自:http://blog.sina.com.cn/s/blog_6748cd1f0100juq8.html

结构体:
#defined MAX_LENGTH 200
typedef struct _TEST_EXAMPLE
{
    char name[MAX_LENGTH+1];
    int age;
} test_example;

结构体的首位置转换成Char指针,比如有10位同学:
test_example *te = (test_example *)malloc(sizeof(test_example) * 10);
//...结构体读取数据..
for (size_t i = 0; i < 10; i ++)
{
te[i].name = student[0];
te[i++].age = student[1];
}
char *result = (char *)te;

当用指针(char *)result做了一些操作后,最后要将Char*指到的首位和长度还原成结构体数组(结构体数组在内存中是连续的);打印结构体如下:
方法一:
size_t value_length = sizeof(test_example) * 10;
for (size_t i = 0; i < value_length; i ++)
{
    printf("%s\t", ((test_example *)(result + i))->name);
    printf("%d\n", ((test_example *)(result + i))->age);
    i += sizeof(test_example) - 1;
}

另外一种方法:
test_example *tmp = (test_example *)result;
for (size_t i = 0; i < value_length / sizeof(test_example); i ++)
{
    printf("%s\t%d\n", (tmp + i)->name, (tmp + i)->age);
}

看起来非常简单,起先我是使用纯指针去截取每个name和age的位置,但是结构体有个问题,随平台不同,结构体每个对象中所占用的空间也不一样,一般是int的整数倍,比如char a[10]是结构的唯一成员变量,其实相当于结构体仍然需要占用12个字节,具体bool这种类型是否也是int的整数倍,需要进行测试确认;所以最好的办法还是使用直接OO的方法指定,虽然指针也是一种OO。

0 0
原创粉丝点击