我想学习嵌套结构体指针的工作原理。如果我要访问一个指向另一个结构体指针中的结构体元素,应该怎么做?谢谢。
#include <iostream>
typedef struct
{
unsigned int a;
unsigned int b;
unsigned int c;
} inner;
typedef struct
{
unsigned int d;
unsigned int e;
inner * in;
} outer;
/* Function to use struct */
void test(outer * out)
{
//Update the value of out->in->a.
out->in->a = 5;
}
int main() {
outer * out;
test(out);
std::cout << "My updated value: " << out->in->a << std::endl;
}
我遇到了"Segmentation fault (core dumped)"的错误。
注:根据建议进行了修改。
#include <iostream>
typedef struct
{
unsigned int a;
unsigned int b;
unsigned int c;
} inner;
typedef struct
{
unsigned int d;
unsigned int e;
inner * in = new inner();
} outer;
/* Function to use struct */
void test(outer * out)
{
//Update the value of out->d.
out->d = 3;
//Update the value of out->in->a.
out->in->a = 5;
}
int main() {
outer out;
outer* p = &out;
test(p);
std::cout << "My updated value for d: " << p->d << std::endl;
std::cout << "My updated value for a: " << p->in->a << std::endl;
}
我现在得到了正确的更新值。但是我现在有一个警告:
"warning: non-static data member initializers only available with -std=c++11 or -std=gnu++11"
inner * in = new inner();
我该如何修复这个警告?
out
的指针。你需要先分配内存。 - Hayt