如何正确的引用一个结构体数组?
在实际应用中遇到一个问题:定义一个结构体stA:
typedef struct _a_
{
uint8 meb1;
uint8 meb2;
}stA;
定义m个结构体数组
const stA Tab1 =
{
{}.
{},
{},
};
const stA Tab2 =
{
{}.
{},
{},
};
.
.
.
const stA Tabm =
{
{}.
{},
{},
};
问题:
选择一种数组定义方式 NameA
要求将结构体数组存放到此数组中,在应用程序中通过调用NameA来访问结构数组中的任意一组数据
例如我要使用Tab2.meb1数据。请给出NameA的定义方式和调用方式。
我是这样使用的,但是结果不对:
定义:
const stA* const NameA[]=//-----is there Error?
{
&Tab1,
&Tab2,
.
.
.
Tabm[],
}
调用:
const stA* ptTest = NULL;
ptTest = *(&NameA + sizeof(NameA)/sizeof(stA*) * 3)//获取Tab2数据----实际这里已经出错了
ptTest->meb1 ++;
请问各位 错误出在哪?
应该如何定义NameA[]?如何获取我期望的Tab2.meb1数据
Thanks!!! #include <stdio.h>
#define uint8 unsigned char
typedef struct _a_
{
uint8 meb1;
uint8 meb2;
}stA;
stA Tab1[] =
{
1,
2
};
stA Tab2[] =
{
3,
4,
};
stA Tabm[] =
{
5,
6,
};
stA* const NameA[]=
{
&Tab1,
&Tab2,
&Tabm,
};
int main(void)
{
stA *p;
int i;
for (i=0; i<3; i++) {
p = NameA;
printf("%d, %d\n", p->meb1, p->meb2);
}
return 0;
}
我在vc中写了点代码,楼主看看
1. 定义:
const stA* const NameA[]=//-----is there Error?
{
&Tab1,
&Tab2,
.
.
.
Tabm[],
}
赋值时候,可加强制类型装换,避免编译器报错,如
const stA* const NameA[]=//-----is there Error?
{
(stA*)&Tab1,
(stA*)&Tab2,
.
.
.
(stA*)Tabm,
}
2. 使用:
可以直接按照数组的方式使用,如:
NameA.mem1 表示访问 数组Tab1的0下标下的结构体的mem1成员.
to 2楼,刚开始就是这么使用的,莫非编译器的问题?
to 3楼,本身NameA的引用就是错误的。 没经测试;我想访问你这样一个数组中的成员大概应该是这个样子!
NameATab1.mem1
页:
[1]