对于初学者来说,C 和 C++ 是不同的语言。
在任何情况下,您都必须在访问其元素抛出指针之前分配结构。否则,使用未初始化的指针或不指向有效结构对象的指针会导致程序的未定义行为。
这是一个演示性 C 程序,展示了如何使用指针访问结构的元素
#include <stdlib.h>
#include <stdio.h>
typedef struct
{
unsigned int a;
unsigned int b;
unsigned int c;
} inner;
typedef struct
{
unsigned int d;
unsigned int e;
inner * in;
} outer;
int main( void )
{
outer *out = malloc( sizeof( outer ) );
if ( ( out != NULL ) && ( out->in = malloc( sizeof( inner ) ) ) )
{
out->in->a = 1;
out->in->b = 2;
out->in->c = 3;
printf( "out->in = { a = %d, b = %d, c = %d }\n", out->in->a, out->in->b, out->in->c );
free( out->in );
free( out );
}
return 0;
}
它的输出是
out->in = { a = 1, b = 2, c = 3 }
在 C++ 中,程序可以是这样的
#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;
int main()
{
outer *out = new outer;
out->in = new inner;
out->in->a = 1;
out->in->b = 2;
out->in->c = 3;
std::cout << "out->in = { a = " << out->in->a
<< ", b = " << out->in->b
<< ", c = " << out->in->c
<< " }" << std::endl;
delete out->in;
delete out;
return 0;
}
其输出将与上图所示相同。
至于这个功能
void test(outer *out)
{
//Update the value of out->in->a.
out->in->a = 5;
}
然后两个指针out
and in
必须指向类型的有效对象outer
and inner
.