gpt4 book ai didi

c++ - 指针和结构

转载 作者:太空宇宙 更新时间:2023-11-03 10:31:28 26 4
gpt4 key购买 nike

我一直在努力思考指针、引用和地址,但每次我想我得到它时,都会弹出一些意想不到的东西。

为什么我们不需要取消引用结构来设置这个例子中的值?

// pointer_tet.cpp
#include <iostream>
struct example
{
char name[20];
int number;
};
int main()
{
using namespace std;
example anExample = {"Test", 5};
example * pt = &anExample;
pt->number = 6;
cout << pt->number << endl;

int anotherExample = 5;
int * pd = &anotherExample;
*pd = 6;
cout << *pd << endl;

return 0;
}

谢谢!

编辑:感谢您的回答!令我困惑的是无法设置 *pt.number = 6。

最佳答案

正在取消引用pt。你正在做:

pt->number = 6;

这相当于:

(*pt).number = 6;

-> 运算符提供了一种通过指针访问成员的便捷方式。

关于c++ - 指针和结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15395334/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com