对象指针的麻烦访问数组 [英] Trouble accessing array of object pointers
问题描述
我正在写一个有点code到一个总线模型。在code有一个错误,我已经简化在下面的代码片段问题:
I'm writing a bit of code to model a bus. The code has an error and I have simplified the problem in the following snippet:
struct luggageTag{
int seat;
bool luggage;
};
int main(){
luggageTag *tagBox[36];
tagBox[2]->luggage = true; // EXC_BAD_ACCESS on this line
}
为什么该行
tagBox[2]->luggage = true;
结果不好的访问?
results in bad access?
推荐答案
一个指针是一个变量就像任何其他的,只是一个指针, T * PTR
,它的值预计是在存储器中的T实例的地址
A pointer is a variable much like any other, except that for a pointer, T* ptr
, its value is expected to be the address of an instance of T in memory.
您已经创建未初始化的变量数组 - 你没有任何东西在他们指出
You've created an array of uninitialized variables - you haven't pointed them at anything.
想想一个指针作为后它音符与它事物的位置。你所做被撕裂36的空白贴字条从堆栈的顶部。
Think of a pointer as a post-it-note with the location of a thing on it. What you've done is torn 36 blank post-it notes off the top of the stack.
您需要创建一些luggageTag的指向,但随后也将负责释放这些对象。
You'll need to create some luggageTag's to point to, but then you'll also be responsible for freeing those objects.
struct luggageTag{
int seat;
bool luggage;
};
int main(){
luggageTag *tagBox[36];
for (size_t i = 0; i < 36; ++i) {
tagBox[i] = new luggageTag;
}
tagBox[2]->luggage = true;
// memory leak unless you do:
// for (size_t i = 0; i < 36 ; ++i)
// delete tagBox[i];
}
另外,您可以创建一个指向36行李标签的数组:
Alternatively you could create a pointer to an array of 36 luggage tags:
struct luggageTag{
int seat;
bool luggage;
};
int main(){
luggageTag *tagBox = new luggageTag[36];
tagBox[2]->luggage = true;
// ...
delete [] tagBox; // free the memory
}
如果这不是一所学校工作的一部分,你可能想看看使用的std ::阵列
或的std ::矢量
。
If this is not part of a school exercise, you might want to look at using a std::array
or std::vector
.
这篇关于对象指针的麻烦访问数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!