创建具有不同类型的元件的阵列 [英] Create an array with elements of different types
问题描述
我要声明,包含不同的变量类型的数组,主要是:
I need to declare an array that consists of different variable types, mainly:
char *A; uint32_t B; int C;
我在教程了解,在数组中声明的类型和元素的数量。这么说来是这样的:
As I understood in the tutorials, in the array you declare the type and the number of element. So to say something like:
int a[3];
,其中在这种情况下,三个元件的类型都是整数。
那么,如何做我想要声明的是由上面提到的三种不同类型的数组?
where in this case, the type of the three elements are all integers. So how do I want to declare an array that consists of the three different types mentioned above?
推荐答案
用C数组的定义是相同类型的元素的集合。可能是你正在寻找一个结构
。
The definition of an array in C is a collection of elements of the SAME type. What you are looking for is probably a struct
.
struct s
{
char* A;
uint32_t B;
int C;
};
int main(void)
{
struct s test;
test.A = "Hello";
test.B = 12345;
test.C = -2;
// Do stuff with 'test'
return 0;
}
或者,如下面的评论中提到,你可以使用联盟
来代替。但你不能使用A,B和C,同时像我在上面的例子 - 只是其中之一将被存储 - 在我的例子这将是C
Or, as mentioned in a comment below, you could use a union
instead. But then you can't use A, B, and C at the same time like I have in the example above - only one of them will be stored - in my example it would be C.
如果你需要,可以使结构数组。
You can make an array of structures if you need to.
struct s test[5]; // Array of structures
这篇关于创建具有不同类型的元件的阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!