[英]Structure pointer assignment in C++
此代碼有什么問題,特別是在檢查功能中? 我在根指針數組中分配了temp1
的地址。 但是我無法從main函數訪問它,盡管它們給出了與輸出相同的地址。
struct block {
int counter=0;
struct block *arr[4];
bool is_leaf;
string val[3];
} root;
void check() {
struct block temp1;
temp1.is_leaf=true;
temp1.val[0]="Sy";
root.arr[1]=&temp1;
cout<<root.arr[1]->val[0]<<endl;
cout<<root.arr[1]<<endl; //block address
}
int main(){
string s1;
root.val[2]=s1;
struct block temp;
temp.val[0]="wewrq";
root.arr[0]=&temp;
check();
cout<<root.arr[0]->val[0]<<endl; // did work
cout<<root.arr[1]<<endl; // same block address
cout<<root.arr[1]->val[0]<<endl; // didn't work
}
在check()
返回之前,限制struct block temp1
的生存期。 一旦check()
返回,就不能再訪問temp1
,即使將其地址存儲在另一個全局結構實例中也是如此。
根據您的實際使用情況,您可以將temp1
聲明為static struct block temp1;
相反,否則您可能需要重新設計代碼結構。
temp1
在退出其作用域時將消失check()
在這種情況下返回功能check()
),因此之后在不調用undefined behavior的情況下不能從main()
函數對其進行訪問。
使它可訪問的方法之一是使變量像
static struct block temp1;
因此在整個程序執行過程中,只會有一個temp1
實例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.