typedef结构数组。他们是如何工作的? [英] typedef struct arrays. How do they work?
问题描述
我已经注意到它们与普通数组的工作方式不同,只是简单地编写
i have noted they don't really work the same as normal arrays that simply write
int x[20]={0};
这将使一个阵列与20 0相继。
但是如果我尝试用struct做同样的事情它会快速向南。
this will make a array with 20 0's after one another.
but if i try to do the same thing with struct's it goes south fast.
typedef struct FancyName {
int x[20];
};
int _tmain(int argc, _tchar* argv[])
{
FancyName Fancy;
Fancy.x={0};
}
以下错误将无法从'int'转换为'int [100]'。
和nomatter我怎么写编译器都不会执行它。
the following errors would be "cannot convert from 'int' to 'int[100]'".
and nomatter how i write the compiler will not execute it.
Fancy.x[]={0};
Fancy.x[0]={0};
Fancy.x={0};
所以我的问题是如何轻松地将结构数组的所有值更改为一个值?
so my question becomes how do i easely change all the values of a struct array to one value?
推荐答案
最简单的方法是
the easiest way is
typedef struct FancyName {
int x[20];
};
FancyName Fancy;
memset( Fancy, 0, sizeof(Fancy) );
另一种方法是将struct和memcopy初始化为另一个
Another way is to initialize a struct and memcopy to another
FancyName source;
source.x[0] = 3; //for illustration
FancyName Fancy;
memcpy( Fancy, source, sizeof(Fancy) );
最后一种方法是在结构数组中进行愚蠢的循环。
你的结构是有意义的,因为它是一个数组。这里的结构更有意义:
The last way is stupid looping in arrays of struxts.
your struct is lagging of sense, because it is an array. structs making more sense like here:
typedef struct ColorPoint{
int x; //coordinate
int y; //coordinate
int z; //coordinate
int color; //color value
float alpha;//alpha value
ColorPoint colorPoint;
colorPoint.x = 1;
colorPoint.y = 2;
colorPoint.z = 3;
colorPoint.color = 0xff;//red
colorPoint.alpha = 0.5; //half transparent
typedef struct FancyName {
int x [20];
};
typedef struct FancyName {
int x[20];
};
使用 C ++
编程语言,你不需要 typedef
。
你可以通过这种方式执行inizialization
Using the C++
programming language, you don't need the typedef
.
You might perform the inizialization to zero this way
FancyName fc = {{0}};
或使用现代 C ++
编译器
or, using a modern C++
compiler
FancyName fc{};
这将默认初始化结构的所有成员(参见 C ++ 11 - 新的ISO C ++标准:统一初始化 [ ^ ])。
这篇关于typedef结构数组。他们是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!