我试图理解指针,所以我编写了这段代码:
#include<iostream>
using namespace std;
struct teste{
int a;
bool b;
};
void say (struct teste* a) {
cout << (*a).a << (*a).b << "\n";
}
int main() {
teste* e;
(*e).a=2;
(*e).b=0;
say(e);
}
这给了我段错误
但以下内容:
#include<iostream>
using namespace std;
struct teste{
int a;
bool b;
};
void say (struct teste* a) {
cout << (*a).a << (*a).b << "\n";
}
int main() {
teste e;
e.a=2;
e.b=0;
say(&e);
}
我知道第二个是首选,但为什么第一个不起作用?我认为我做的一切都很好。
最佳答案
teste* e;
(*e).a=2;
(*e).b=0;
这会导致段错误,因为指针 e
未初始化 - 它未指向有效内存。
当您使用某个地址初始化指针时,比如 y
- 然后应用取消引用运算符,您告诉它从您分配给它的内存地址 y
中检索值。在你的例子中,没有地址被分配给它,所以你不能取消引用它。
让它指向一个teste
对象,然后你就可以解引用它。
关于c++ - 关于从结构指针读取的代码的简单代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35245514/