说如果我有两种结构类型:
typedef struct
{
unsigned int * a;
char * b;
char * c;
}TYPEA;
typedef struct
{
unsigned int * a;
unsigned int * b;
}TYPEB;
而且我还有一个指针数组,其中包含指向TYPEA
类型的指针:
TYPEA* AArray[1] =
{
&ga,
};
ga
定义为:
TYPEA ga =
{
&num1,
&b,
&c,
};
如果我TYPEA
定义了另一个 var,我可以修改AArray[0]
内容的值,如下所示:
TYPEA another_ga =
{
&num3,
&b,
&c,
};
void change_AArray()
{
*AArray[0] = another_ga;
}
这很好用,但问题是,因为TYPEA
和TYPEB
的前 32 位是相同的(两者都是unsigned int
),我是否可以将AArray
'ga
的内容更改为TYPEB
结构?
这是我的尝试:
void change_AArray()
{
/* *AArray[0] = another_ga; */
/* Compile Error */
/* *AArray[0] = gb; */
/* Compile Error */
/* *AArray[0] = (TYPEA)gb; */
/* Passed compile, but AArray[0] is not changed */
/* AArray[0] = (TYPEA*)&gb; */
}
然后我尝试添加另一个指针并将其放入AArray[0]
而不是 using &ga
,但它无法通过编译阶段,我认为 C 在初始化列表中需要一个常量。
TYPEA * pga = &ga;
TYPEA* AArray[1] =
{
pga, // error, needs a constant expression.
};
void change_AArray()
{
AArray[0] = (TYPEA*)&gb;
}
是否可以进行类型转换?
整个代码:
#include <stdio.h>
typedef struct
{
unsigned int * a;
char * b;
char * c;
}TYPEA;
typedef struct
{
unsigned int * a;
unsigned int * b;
}TYPEB;
int num1 = 10, num2 = 20, num3 = 30;
char b = 'b', c = 'c';
TYPEA ga =
{
&num1,
&b,
&c,
};
TYPEA another_ga =
{
&num3,
&b,
&c,
};
TYPEB gb =
{
&num2,
&num3,
};
TYPEA* AArray[1] =
{
&ga,
};
void change_AArray()
{
*AArray[0] = another_ga;
/* How can I do this conversion? */
/* *AArray[0] = gb; */
}
int main(int argc, const char *argv[])
{
printf("ga.a: %d\n", *ga.a);
printf("gb.b: %d\n", *gb.a);
change_AArray();
printf("After calling change_AArray()\n");
printf("ga.a: %d\n", *ga.a);
printf("gb.b: %d\n", *gb.a);
return 0;
}