结构数组动态分配 [英] array of structures dynamic allocation
本文介绍了结构数组动态分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
大家好,
有人请向我解释如何动态分配和结构数组
例如这个结构
typedef struct
{
float angle; // 当前伺服角度
unsigned int16 width_count;
float min_angle; // min achieve vable angle
float max_angle; // 最大可实现角度
int16 min_uswidth;
int16 max_uswidth;
} servo_motor;
servo_motor servo [ 4 ];
提前谢谢,
z3ngew
解决方案
这是malloc
,请参阅:
http://www.cplusplus.com/forum/articles/416/ [ ^ ]。
请不要忘记免费
。
为什么你的东西是你的分配应该是动态的吗?你没有可变数量的结构;在你的代码中,它是立即常量 4,顺便说一下,它总是很糟糕。你应该有明确的const
。在这种情况下,您可以简单地声明数组,并且它将在堆栈上分配,直到您离开上层堆栈帧时才会被删除。
-SA
这里: 7.2将数组传递给函数 [ ^ ]你会找到一个例子
我在这里找到了一个很好的答案
http://cboard.cprogramming.com/cplusplus-programming/80630-passing-struct- function-reference.html [ ^ ]
Hello everyone,
will someone please explain to me how to dynamically allocate and array of structures
for example this structure
typedef struct
{
float angle; //current servo angle
unsigned int16 width_count;
float min_angle; //min achievable angle
float max_angle; //max achievable angle
int16 min_uswidth;
int16 max_uswidth;
}servo_motor;
servo_motor servo[4];
thanks in advance,
z3ngew
解决方案
It'smalloc
, please see:
http://www.cplusplus.com/forum/articles/416/[^].
Please don't forgetfree
.
Why do you thing your allocation should be dynamic? You don't have variable number of structures; in your code, it's the immediate constant 4, which is, by the way, always bad. You should have explicitconst
. In this case, you can simply declare the array, and it will be allocated on stack and not removed until you leave for a upper-level stack frame.
—SA
Here: 7.2 Passing Arrays to Functions[^] you'll find an example
i found a good answer here
http://cboard.cprogramming.com/cplusplus-programming/80630-passing-struct-function-reference.html[^]
这篇关于结构数组动态分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文