您好我遇到了一些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;
内存中发生了什么?答案 0 :(得分:3)
从堆栈分配足够的内存来存储内存地址。这将是32位或64位,具体取决于您的操作系统。
mypointer
是堆栈中包含内存地址的变量。
*mypointer
是mypointer
指向的实际内存位置。
值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;
}
答案 1 :(得分:2)
答案 2 :(得分:1)
答案 3 :(得分:1)
int * mypointer;
它是一个声明..它告诉编译器我们将使用mypointer作为整数指针变量。
mypointer =&amp; firstvalue;
这里firstvalue的地址存储在mypointer中。
* mypointer = 10;
考虑mypointer指向地址位置4000.现在值10存储在地址位置4000中。
任何其他疑问请与我沟通
答案 4 :(得分:1)
声明int * mypointer时内存中究竟发生了什么;宣布?
mypointer
保存int的地址。因此,保存整数地址所需的字节数被分配给mypointer
。
mypointer代表什么?
它是一个可以保存整数变量地址的变量。
* mypointer代表什么?
它取消引用指针。获取地址位置mypointer
的值。
当* mypointer = 10时;记忆中会发生什么?
在10
位置分配值mypointer
。
答案 5 :(得分:1)
int *mypointer
时,它声明一个指针类型(一个长整数),它可以包含一个整数的内存地址。mypointer
表示整数的地址,其方式与街道地址代表街道上的房屋非常相似。*mypointer
取消引用地址并指向int的实际值。这与地址指向的实际房屋类似。