- 究竟發生在內存什麼時int * mypointer;被宣佈?
從棧中分配足夠的內存來存儲內存地址。這將是32或64位,具體取決於您的操作系統。
- mypointer代表什麼?
mypointer
是包含存儲器地址的堆棧上的變量。
- * mypointer代表什麼?
*mypointer
是由mypointer
指向的實際存儲位置。
- 當* mypointer = 10;記憶中發生了什麼?
值10
存儲在mypointer
指向的內存位置。例如,如果mypointer
包含存儲器地址0x00004000
,則值10
被存儲在存儲器中的該位置處。
你有意見例如:
int main()
{
int firstvalue, secondvalue; // declares two integer variables on the stack
int * mypointer; // declares a pointer-to-int variable on the stack
mypointer = &firstvalue; // sets mypointer to the address of firstvalue
*mypointer = 10; // sets the location pointed to by mypointer to 10.
In this case same as firstvalue = 10; because
mypointer contains the address of firstvalue
mypointer = &secondvalue; // sets mypointer to the address of secondvalue
*mypointer = 20; // sets the location pointed to by mypointer to 10.
In this case same as secondvalue = 20; because
mypointer contains the address of secondvalue
cout << "firstvalue is " << firstvalue << endl;
cout << "secondvalue is " << secondvalue << endl;
return 0;
}
試試這個代碼,看看是否有幫助:
int main()
{
int firstvalue, secondvalue;
int * mypointer;
cout << "firstvalue is " << firstvalue << endl;
cout << "secondvalue is " << secondvalue << endl;
cout << "mypointer is pointing to " << mypointer << endl;
mypointer = &firstvalue;
cout << "firstvalue is " << firstvalue << endl;
cout << "secondvalue is " << secondvalue << endl;
cout << "mypointer is pointing to " << mypointer << endl;
*mypointer = 10;
cout << "firstvalue is " << firstvalue << endl;
cout << "secondvalue is " << secondvalue << endl;
cout << "mypointer is pointing to " << mypointer << endl;
mypointer = &secondvalue;
cout << "firstvalue is " << firstvalue << endl;
cout << "secondvalue is " << secondvalue << endl;
cout << "mypointer is pointing to " << mypointer << endl;
*mypointer = 20;
cout << "firstvalue is " << firstvalue << endl;
cout << "secondvalue is " << secondvalue << endl;
cout << "mypointer is pointing to " << mypointer << endl;
return 0;
}
發佈新的問題,請搜索。這個問題的答案應該告訴你一切你需要知道的指針:[理解C++指針](http://stackoverflow.com/questions/5727/what-are-the-barriers-to-understanding-pointers-and-什麼是可以做到克服) – 2011-04-07 05:22:09
我看到那篇文章,但仍然困惑,所以我想我會嘗試召喚出另一個例子,並試圖理解它。 – locoboy 2011-04-07 05:25:26