嗨,我遇到了这段C ++代码,并试图了解指针的操作方式。
int main ()
{
int firstvalue, secondvalue;
int * mypointer;
mypointer = &firstvalue;
*mypointer = 10;
mypointer = &secondvalue;
*mypointer = 20;
cout << "firstvalue is " << firstvalue << endl;
cout << "secondvalue is " << secondvalue << endl;
return 0;
}
我的问题如下:
声明
int *mypointer;
时,内存中到底发生了什么?mypointer
代表什么?*mypointer
代表什么?什么时候
*mypointer = 10;
内存中发生了什么? 最佳答案
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++ - 通过实例学习指针,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5576334/