[英]Trouble accessing array of object pointers
我正在寫一些代碼來建模總線。 代碼有錯誤,我在以下代碼段中簡化了該問題:
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;
導致訪問錯誤?
因為tagBox[2]
是一個指針,但是它沒有指向任何地方,因此您試圖取消引用它。
您需要首先將其指向某個位置,例如:
luggageTag tag;
tagBox[2] = &tag;
但是除非有特定的原因為什么您需要指針,否則您可以直接將實際對象直接存儲在數組中:
luggageTag tagBox[36];
// ^ remove *
tagBox[2].luggage = true; // no EXC_BAD_ACCESS!
// ^ dot, not arrow operator
現在,無需首先將數組元素指向某個對象。
指針是一個非常類似於其他變量的變量,除了對於指針T* ptr
,它的值應該是內存中T實例的地址。
您已經創建了一個未初始化變量的數組-您沒有將它們指向任何對象。
可以將指針視為便箋,上面有事物的位置。 您要做的是從堆棧頂部撕下36張空白便箋。
您需要創建一些指向的箱包標簽,但是您還需要負責釋放那些對象。
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個行李牌數組的指針:
struct luggageTag{
int seat;
bool luggage;
};
int main(){
luggageTag *tagBox = new luggageTag[36];
tagBox[2]->luggage = true;
// ...
delete [] tagBox; // free the memory
}
如果這不是學校活動的一部分,則可能需要使用std::array
或std::vector
進行查看。
您需要分配數組中的所有對象:
luggageTag *tagBox[36];
for(int i=0; i<36; i++)
tagBox[i] = new luggageTag;
tagBox[2]->luggage = true;
for(int i=0; i<36;i++)
delete tagBox[i];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.