提问人:agutier2 提问时间:7/20/2022 最后编辑:Vlad from Moscowagutier2 更新时间:7/20/2022 访问量:84
带指针的结构 [已关闭]
Structures with pointers [closed]
问:
所以我有一个叫做 Shield 的结构,里面有三个指针。我需要事先用其中一个指针填充数据,并且我需要在一个常量循环中访问这些数据。我遇到的问题是,每当我尝试访问指针中应该包含的内容时,我的程序就会崩溃。这是我的结构
struct Shield{
esat::Vec3 *circle;
esat::Vec2 *walls;
bool *isActive;
};
其中 esat::Vec3 和 esat::Vec2 只是带有表示向量的浮点数的结构。
我在函数中初始化指针,该函数将 Shield 对象作为参数,并填充我需要的指针数据。
void InitShield(Shield shield){
shield.circle = (esat::Vec3*) malloc((KVertices + 1) * sizeof(esat::Vec3));
shield.walls = (esat::Vec2*) malloc((KVertices + 1) * sizeof(esat::Vec2));
shield.isActive = (bool*) malloc((KVertices + 1) * sizeof(bool));
float angle = 6.28f / KVertices;
for(int i=0; i<KVertices; ++i){
(*(shield.circle + i)).x = cos(angle * i);
(*(shield.circle + i)).y = sin(angle * i);
(*(shield.circle + i)).z = 1.0f;
(*(shield.isActive + i)) = true;
}
}
然后我尝试访问我应该存储在指针中的内容。
void DrawCircle(esat::Mat3 base, esat::Vec2 *tr_points, esat::Vec3 *circle, bool *checkActive){
CheckShield(first_shield);
for(int i=0; i<KVertices; ++i){
esat::Vec3 points = esat::Mat3TransformVec3(base, (*(circle + i)));
*(tr_points + i) = {points.x, points.y};
}
for(int i=0; i<KVertices; ++i){
if((*(checkActive + i)) == true){
esat::DrawSetStrokeColor(color.r, color.g, color.b);
esat::DrawLine((*(tr_points + i)).x, (*(tr_points + i)).y, (*(tr_points + ((i+1)%KVertices))).x, (*(tr_points + ((i+1)%KVertices))).y);
}
}
}
这是我的程序崩溃的地方。当我尝试访问我的圆指针内应该包含的内容时,程序失败并崩溃。 有谁知道我做错了什么?我还没弄清楚。
答:
0赞
Vlad from Moscow
7/20/2022
#1
此函数接受 Shield by value 类型的对象。
void InitShield(Shield shield){
也就是说,该函数处理传递的参数值的副本。
在函数中更改副本不会影响原始对象。
如果您使用的是 C++,则至少声明该函数
void InitShield(Shield &shield){
并使用运算符而不是直接调用。new
malloc
如果您使用的是 C,则声明如下函数
void InitShield(Shield *shield){
此外,还不清楚为什么要分配对象,例如KVertices + 1
shield.circle = (esat::Vec3*) malloc((KVertices + 1) * sizeof(esat::Vec3));
但下面的 for 循环只使用迭代。KVertices
for(int i=0; i<KVertices; ++i){
评论
0赞
agutier2
7/20/2022
我认为这奏效了!我的程序不再崩溃了,谢谢。现在我明白了,这很有意义。
下一个:C++ 列表函数不旋转
评论
esat::Vec3
在标准 C 中看起来语法无效。我将标签更改为 C++。std::vector
*(ptr + i) == ptr[i]
malloc
InitShield
需要接受作为参考,不是吗?shield
std::vector