结构体数组和Char指针之间的转换

对C的指针一直有所欠缺,这里学到一些皮毛,分享一下:

结构体:
#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。




Categories

| | 评论(0)

发表评论

June 2011

      1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30    

关于此日记

此日记由 Cnangel 发表于 May 12, 2008 4:11 PM

此Blog上的上一篇日记回忆——一张很久的照片

此Blog上的下一篇日记一些标准的信号

首页归档页可以看到最新的日记和所有日记。

归档

Powered by Movable Type 5.11