1

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); 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 .

#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;
}

1 Answer 1

2

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 . 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’)

I.e. the node1 is used to initialize data[0].hope[0].innercount which is an integer.

The warning from GCC explains it very clearly.

Now, to initialize this I believe in C99+ you could use

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

struct MyData data[1] = {{3, {{1, "helo"}}, 1.0}};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.