[英]Accessing a struct with an array of structs variables
I want to make a Struct of an array of structs.I tried to change one of the structs field variables of the array of structs.Node( [ Node(1,[]) | | | ] )** I don't understand why my struct array hope first node count isn't equal to 1. When I printf("%d\\n",start->innercount); 我想制作一个结构数组的结构。我试图更改该结构数组的结构字段变量之一。Node([ Node(1,[]) | | |])**我不明白为什么我的struct数组希望第一个节点数不等于1。当我printf(“%d \\ n”,start-> innercount); I expect 1 because my node1 fields innercount has been initialized to 1 and I have initialized hope struct fields to 3,node1,1.0 .
我希望1,因为我的innercount已经被初始化到1,我已经初始化希望结构域3,node1,1.0 节点1场。
#include <stdio.h>
struct Mynode {
int innercount;
char token[20];
};
struct MyData {
int count;
struct Mynode hope[20];
float average;
};
int main(){
struct Mynode node1[1] = {1, "helo"};
struct MyData data[1] = {3, node1, 1.0};
struct MyData* ptr = data;
struct MyData* endPtr = data + sizeof(data) / sizeof(data[0]);
while ( ptr < endPtr ){
struct Mynode* start = ptr->hope;
struct Mynode* end = ptr->hope + sizeof(ptr->hope) / sizeof(ptr->hope[0]);
while(start < end){
printf("%d\n",start->innercount);
start++;
}
ptr++;
}
return 0;
}
You cannot initialize an array with an array like this. 你不能用一个这样的数组初始化数组 。 Instead, the C89-style initializer expects you to spell out all the fields of the aggregate .
取而代之的是,C89样式的初始值设定项要求您拼写聚合的所有字段。 Check your compiler output and warning settings.
检查您的编译器输出和警告设置。 Specifically:
特别:
% gcc strcut.c
strcut.c: In function ‘main’:
strcut.c:15:30: warning: initialization makes integer from pointer without a cast [-Wint-conversion]
struct MyData data[1] = {3, node1, 1.0};
^~~~~
strcut.c:15:30: note: (near initialization for ‘data[0].hope[0].innercount’)
Ie the node1
is used to initialize data[0].hope[0].innercount
which is an integer. 即,
node1
用于初始化data[0].hope[0].innercount
,它是一个整数。
The warning from GCC explains it very clearly. 来自GCC的警告非常清楚地说明了这一点。
Now, to initialize this I believe in C99+ you could use 现在,要初始化它,我相信您可以使用C99 +
struct Mynode node1[1] = {{1,"helo"}};
struct MyData data[1] = {{3, {[0] = node1[0]}, 1.0}};
at least it works for me . 至少对我有用 。 However I am not sure if it is standards-compliant.
但是,我不确定它是否符合标准。 In C89 you'd have to initialize the inner structure in place
在C89中,您必须在适当的位置初始化内部结构
struct MyData data[1] = {{3, {{1, "helo"}}, 1.0}};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.