访问结构内的数组

时间:2016-06-16 16:13:49

标签: c arrays struct

如何访问结构中的数组,让我们说:

struct example
{
double qe[2];
double qw[2];
};

double a[2], b[2];

struct example1 ={a,b};

如何打印[0]作为示例? 如何使用指向结构example1的指针打印[0]?

2 个答案:

答案 0 :(得分:2)

首先,

struct example1 = ...;

不正确。你需要使用:

struct example example1 = ...;

即使这样,你也不能使用

struct example example1 = {a,b};

初始化example1。这在语法上是不正确的。您需要使用其他方法将ab的内容复制到example1

如果example1有自动存储时间,您可以使用

方法1:

struct example example1 = { {a[0], a[1]}, {b[0], b[1]} };

否则,您必须使用:

方法2:

struct example example1;

在某些功能中:

example1.qe[0] = a[0];
example1.qe[1] = a[1];
example1.qw[0] = b[0];
example1.qw[1] = b[1];

或,方法3:

struct example example1;

在某些功能中:

memcpy(example1.qe, a, sizeof(a));
memcpy(example1.qw, b, sizeof(b));

答案 1 :(得分:0)

谢谢R Sahu,我看到了我的错误。这确实是数组的错误声明和结构的allignment。 struct example example1 = { {a[0], a[1]}, {b[0], b[1]} };工作了。

相关问题