How do you make an array of structs in C? Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) Data science time! April 2019 and salary with experience Should we burninate the [wrap] tag? The Ask Question Wizard is Live!an array of people using structs in c?C - initialize array of structsArray of structs in CSetting a struct to an array in an AVRFunction pointer in struct args?have a loop to create structsC Replacing Variable NumberArray of struct implementation in CReturn two values with pop function from priority queueHow to print specific data in c?Create ArrayList from arrayHow do I check if an array includes an object in JavaScript?How to append something to an array?How to insert an item into an array at a specific index (JavaScript)?How do you check if a variable is an array in JavaScript?How do I empty an array in JavaScript?Loop through an array in JavaScriptHow to check if an object is an array?How do I remove a particular element from an array in JavaScript?For-each over an array in JavaScript?

Antler Helmet: Can it work?

How much radiation do nuclear physics experiments expose researchers to nowadays?

Do you forfeit tax refunds/credits if you aren't required to and don't file by April 15?

Did Kevin spill real chili?

Should I call the interviewer directly, if HR aren't responding?

Were Kohanim forbidden from serving in King David's army?

If a contract sometimes uses the wrong name, is it still valid?

What are the pros and cons of Aerospike nosecones?

Letter Boxed validator

What is the longest distance a 13th-level monk can jump while attacking on the same turn?

Why does Python start at index -1 when indexing a list from the end?

Why constant symbols in a language?

Is the address of a local variable a constexpr?

What do you call a plan that's an alternative plan in case your initial plan fails?

Why did the IBM 650 use bi-quinary?

What are the motives behind Cersei's orders given to Bronn?

Is there a documented rationale why the House Ways and Means chairman can demand tax info?

Why is "Consequences inflicted." not a sentence?

Stars Make Stars

How to motivate offshore teams and trust them to deliver?

Why was the term "discrete" used in discrete logarithm?

iPhone Wallpaper?

Determinant is linear as a function of each of the rows of the matrix.

Sorting numerically



How do you make an array of structs in C?



Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)
Data science time! April 2019 and salary with experience
Should we burninate the [wrap] tag?
The Ask Question Wizard is Live!an array of people using structs in c?C - initialize array of structsArray of structs in CSetting a struct to an array in an AVRFunction pointer in struct args?have a loop to create structsC Replacing Variable NumberArray of struct implementation in CReturn two values with pop function from priority queueHow to print specific data in c?Create ArrayList from arrayHow do I check if an array includes an object in JavaScript?How to append something to an array?How to insert an item into an array at a specific index (JavaScript)?How do you check if a variable is an array in JavaScript?How do I empty an array in JavaScript?Loop through an array in JavaScriptHow to check if an object is an array?How do I remove a particular element from an array in JavaScript?For-each over an array in JavaScript?



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








82















I'm trying to make an array of structs where each struct represents a celestial body.



I don't have that much experience with structs, which is why I decided to try to use them instead of a whole bunch of arrays. However, I keep on running into numerous different errors. I've tried to implement the techniques that I've seen on various threads and on StackOverflow (such as Array of structs in C and C - initialize array of structs), however not all of them were applicable.



Further information for those who have read this far: I don't need any of this to be dynamic, I know/define the size of everything beforehand. I also need this to be a global array as I'm accessing this in several different methods which have defined arguments (i.e. GLUT methods).



This is how I'm defining the struct in my header:



struct body

double p[3];//position
double v[3];//velocity
double a[3];//acceleration
double radius;
double mass;
;


I have a list of other global variables that I'm defining before I define the interior of the struct, and one of those is the array of this struct (basically, if I'm being too unclear in my fogged speak, the line below is above the stuff above):



struct body bodies[n];


Just so you know, n is something that I've legitimately defined (i.e. #define n 1).



I use this array in several different methods, but the easiest and least space consuming one is a simplified form of my main. Here I initialize all of the variables in each of the structs, just to set the variables for certain before I modify them in some way:



 int a, b;
for(a = 0; a < n; a++)

for(b = 0; b < 3; b++)

bodies[a].p[b] = 0;
bodies[a].v[b] = 0;
bodies[a].a[b] = 0;

bodies[a].mass = 0;
bodies[a].radius = 1.0;



The current error that I'm facing is nbody.c:32:13: error: array type has incomplete element type where line 32 is where I'm making the array of the structs.



One last clarification, by header I mean the space above int main(void) but in the same *.c file.










share|improve this question
























  • Well, it works fine for me. Aren't you declaring struct body bodies[n]; before struct body declaration?

    – Jack
    May 6 '12 at 4:50


















82















I'm trying to make an array of structs where each struct represents a celestial body.



I don't have that much experience with structs, which is why I decided to try to use them instead of a whole bunch of arrays. However, I keep on running into numerous different errors. I've tried to implement the techniques that I've seen on various threads and on StackOverflow (such as Array of structs in C and C - initialize array of structs), however not all of them were applicable.



Further information for those who have read this far: I don't need any of this to be dynamic, I know/define the size of everything beforehand. I also need this to be a global array as I'm accessing this in several different methods which have defined arguments (i.e. GLUT methods).



This is how I'm defining the struct in my header:



struct body

double p[3];//position
double v[3];//velocity
double a[3];//acceleration
double radius;
double mass;
;


I have a list of other global variables that I'm defining before I define the interior of the struct, and one of those is the array of this struct (basically, if I'm being too unclear in my fogged speak, the line below is above the stuff above):



struct body bodies[n];


Just so you know, n is something that I've legitimately defined (i.e. #define n 1).



I use this array in several different methods, but the easiest and least space consuming one is a simplified form of my main. Here I initialize all of the variables in each of the structs, just to set the variables for certain before I modify them in some way:



 int a, b;
for(a = 0; a < n; a++)

for(b = 0; b < 3; b++)

bodies[a].p[b] = 0;
bodies[a].v[b] = 0;
bodies[a].a[b] = 0;

bodies[a].mass = 0;
bodies[a].radius = 1.0;



The current error that I'm facing is nbody.c:32:13: error: array type has incomplete element type where line 32 is where I'm making the array of the structs.



One last clarification, by header I mean the space above int main(void) but in the same *.c file.










share|improve this question
























  • Well, it works fine for me. Aren't you declaring struct body bodies[n]; before struct body declaration?

    – Jack
    May 6 '12 at 4:50














82












82








82


33






I'm trying to make an array of structs where each struct represents a celestial body.



I don't have that much experience with structs, which is why I decided to try to use them instead of a whole bunch of arrays. However, I keep on running into numerous different errors. I've tried to implement the techniques that I've seen on various threads and on StackOverflow (such as Array of structs in C and C - initialize array of structs), however not all of them were applicable.



Further information for those who have read this far: I don't need any of this to be dynamic, I know/define the size of everything beforehand. I also need this to be a global array as I'm accessing this in several different methods which have defined arguments (i.e. GLUT methods).



This is how I'm defining the struct in my header:



struct body

double p[3];//position
double v[3];//velocity
double a[3];//acceleration
double radius;
double mass;
;


I have a list of other global variables that I'm defining before I define the interior of the struct, and one of those is the array of this struct (basically, if I'm being too unclear in my fogged speak, the line below is above the stuff above):



struct body bodies[n];


Just so you know, n is something that I've legitimately defined (i.e. #define n 1).



I use this array in several different methods, but the easiest and least space consuming one is a simplified form of my main. Here I initialize all of the variables in each of the structs, just to set the variables for certain before I modify them in some way:



 int a, b;
for(a = 0; a < n; a++)

for(b = 0; b < 3; b++)

bodies[a].p[b] = 0;
bodies[a].v[b] = 0;
bodies[a].a[b] = 0;

bodies[a].mass = 0;
bodies[a].radius = 1.0;



The current error that I'm facing is nbody.c:32:13: error: array type has incomplete element type where line 32 is where I'm making the array of the structs.



One last clarification, by header I mean the space above int main(void) but in the same *.c file.










share|improve this question
















I'm trying to make an array of structs where each struct represents a celestial body.



I don't have that much experience with structs, which is why I decided to try to use them instead of a whole bunch of arrays. However, I keep on running into numerous different errors. I've tried to implement the techniques that I've seen on various threads and on StackOverflow (such as Array of structs in C and C - initialize array of structs), however not all of them were applicable.



Further information for those who have read this far: I don't need any of this to be dynamic, I know/define the size of everything beforehand. I also need this to be a global array as I'm accessing this in several different methods which have defined arguments (i.e. GLUT methods).



This is how I'm defining the struct in my header:



struct body

double p[3];//position
double v[3];//velocity
double a[3];//acceleration
double radius;
double mass;
;


I have a list of other global variables that I'm defining before I define the interior of the struct, and one of those is the array of this struct (basically, if I'm being too unclear in my fogged speak, the line below is above the stuff above):



struct body bodies[n];


Just so you know, n is something that I've legitimately defined (i.e. #define n 1).



I use this array in several different methods, but the easiest and least space consuming one is a simplified form of my main. Here I initialize all of the variables in each of the structs, just to set the variables for certain before I modify them in some way:



 int a, b;
for(a = 0; a < n; a++)

for(b = 0; b < 3; b++)

bodies[a].p[b] = 0;
bodies[a].v[b] = 0;
bodies[a].a[b] = 0;

bodies[a].mass = 0;
bodies[a].radius = 1.0;



The current error that I'm facing is nbody.c:32:13: error: array type has incomplete element type where line 32 is where I'm making the array of the structs.



One last clarification, by header I mean the space above int main(void) but in the same *.c file.







c arrays struct






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 8 at 16:34









Seanny123

2,70443870




2,70443870










asked May 6 '12 at 4:35









Amndeep7Amndeep7

85431123




85431123












  • Well, it works fine for me. Aren't you declaring struct body bodies[n]; before struct body declaration?

    – Jack
    May 6 '12 at 4:50


















  • Well, it works fine for me. Aren't you declaring struct body bodies[n]; before struct body declaration?

    – Jack
    May 6 '12 at 4:50

















Well, it works fine for me. Aren't you declaring struct body bodies[n]; before struct body declaration?

– Jack
May 6 '12 at 4:50






Well, it works fine for me. Aren't you declaring struct body bodies[n]; before struct body declaration?

– Jack
May 6 '12 at 4:50













7 Answers
7






active

oldest

votes


















90














#include<stdio.h>
#define n 3
struct body

double p[3];//position
double v[3];//velocity
double a[3];//acceleration
double radius;
double mass;
;

struct body bodies[n];

int main()

int a, b;
for(a = 0; a < n; a++)

for(b = 0; b < 3; b++)

bodies[a].p[b] = 0;
bodies[a].v[b] = 0;
bodies[a].a[b] = 0;

bodies[a].mass = 0;
bodies[a].radius = 1.0;


return 0;



this works fine. your question was not very clear by the way, so match the layout of your source code with the above.






share|improve this answer

























  • Also, I have a question about the placement between the declaration of the struct type and then actually making an instance of it - I have a different struct, one that I defined the contents of below where I first make an instance of it (just one this time, not an array), so why didn't this make the massive series of errors? It worked just fine, which led me to think that my attempt at making an array should have worked as well, but this time it didn't work. Also, thank you for your answer, it worked.

    – Amndeep7
    May 6 '12 at 15:07











  • Thanks!!!, this really help me!

    – FlokiTheFisherman
    Jul 24 '16 at 0:53






  • 1





    Hi, .... 59 likes ? I didn't see arrays of struct, I only see arrays of variable from struck...

    – delive
    Mar 15 '17 at 23:10



















10














I think you could write it that way too. I am also a student so I understand your struggle. A bit late response but ok .



#include<stdio.h>
#define n 3

struct
double p[3];//position
double v[3];//velocity
double a[3];//acceleration
double radius;
double mass;
bodies[n];





share|improve this answer






























    8














    move



    struct body bodies[n];


    to after



    struct body

    double p[3];//position
    double v[3];//velocity
    double a[3];//acceleration
    double radius;
    double mass;
    ;


    Rest all looks fine.






    share|improve this answer






























      8














      So to put it all together by using malloc():



      int main(int argc, char** argv) 
      typedef struct
      char* firstName;
      char* lastName;
      int day;
      int month;
      int year;

      STUDENT;

      int numStudents=3;
      int x;
      STUDENT* students = malloc(numStudents * sizeof *students);
      for (x = 0; x < numStudents; x++)
      students[x].firstName=(char*)malloc(sizeof(char*));
      scanf("%s",students[x].firstName);
      students[x].lastName=(char*)malloc(sizeof(char*));
      scanf("%s",students[x].lastName);
      scanf("%d",&students[x].day);
      scanf("%d",&students[x].month);
      scanf("%d",&students[x].year);


      for (x = 0; x < numStudents; x++)
      printf("first name: %s, surname: %s, day: %d, month: %d, year: %dn",students[x].firstName,students[x].lastName,students[x].day,students[x].month,students[x].year);

      return (EXIT_SUCCESS);






      share|improve this answer




















      • 7





        Should your malloc line have numStudents * sizeof(STUDENT)?

        – Todd
        Jul 24 '14 at 16:57











      • @Todd It's better not to. sizeof *students is the same thing and it won't be wrong if STUDENT ever happens to change.

        – trentcl
        Mar 11 '16 at 18:18


















      1














      That error means that the compiler is not able to find the definition of the type of your struct before the declaration of the array of structs, since you're saying you have the definition of the struct in a header file and the error is in nbody.c then you should check if you're including correctly the header file.
      Check your #include's and make sure the definition of the struct is done before declaring any variable of that type.






      share|improve this answer























      • i doubt OP means header as header file, as he wrote, "the line below is above the stuff above" before the struct array declaration which is in his nbody.c file. Lets wait for him to wake up and clear the doubt.

        – nims
        May 6 '12 at 4:52












      • @nims is correct, by header I meant the area above the main statement.

        – Amndeep7
        May 6 '12 at 14:39


















      0














      Solution using pointers:



      #include<stdio.h>
      #include<stdlib.h>
      #define n 3
      struct body

      double p[3];//position
      double v[3];//velocity
      double a[3];//acceleration
      double radius;
      double *mass;
      ;


      int main()

      struct body *bodies = (struct body*)malloc(n*sizeof(struct body));
      int a, b;
      for(a = 0; a < n; a++)

      for(b = 0; b < 3; b++)

      bodies[a].p[b] = 0;
      bodies[a].v[b] = 0;
      bodies[a].a[b] = 0;

      bodies[a].mass = 0;
      bodies[a].radius = 1.0;


      return 0;






      share|improve this answer






























        0














        Another way of initializing an array of structs is to initialize the array members explicitly. This approach is useful and simple if there aren't too many struct and array members.



        Use the typedef specifier to avoid re-using the struct statement everytime you declare a struct variable:



        typedef struct

        double p[3];//position
        double v[3];//velocity
        double a[3];//acceleration
        double radius;
        double mass;
        Body;


        Then declare your array of structs. Initialization of each element goes along with the declaration:



        Body bodies[n] = 0,0,0, 0,0,0, 0,0,0, 0, 1.0, 
        0,0,0, 0,0,0, 0,0,0, 0, 1.0,
        0,0,0, 0,0,0, 0,0,0, 0, 1.0;


        To repeat, this is a rather simple and straightforward solution if you don't have too many array elements and large struct members and if you, as you stated, are not interested in a more dynamic approach. This approach can also be useful if the struct members are initialized with named enum-variables (and not just numbers like the example above) whereby it gives the code-reader a better overview of the purpose and function of a structure and its members in certain applications.






        share|improve this answer























          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f10468128%2fhow-do-you-make-an-array-of-structs-in-c%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          7 Answers
          7






          active

          oldest

          votes








          7 Answers
          7






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          90














          #include<stdio.h>
          #define n 3
          struct body

          double p[3];//position
          double v[3];//velocity
          double a[3];//acceleration
          double radius;
          double mass;
          ;

          struct body bodies[n];

          int main()

          int a, b;
          for(a = 0; a < n; a++)

          for(b = 0; b < 3; b++)

          bodies[a].p[b] = 0;
          bodies[a].v[b] = 0;
          bodies[a].a[b] = 0;

          bodies[a].mass = 0;
          bodies[a].radius = 1.0;


          return 0;



          this works fine. your question was not very clear by the way, so match the layout of your source code with the above.






          share|improve this answer

























          • Also, I have a question about the placement between the declaration of the struct type and then actually making an instance of it - I have a different struct, one that I defined the contents of below where I first make an instance of it (just one this time, not an array), so why didn't this make the massive series of errors? It worked just fine, which led me to think that my attempt at making an array should have worked as well, but this time it didn't work. Also, thank you for your answer, it worked.

            – Amndeep7
            May 6 '12 at 15:07











          • Thanks!!!, this really help me!

            – FlokiTheFisherman
            Jul 24 '16 at 0:53






          • 1





            Hi, .... 59 likes ? I didn't see arrays of struct, I only see arrays of variable from struck...

            – delive
            Mar 15 '17 at 23:10
















          90














          #include<stdio.h>
          #define n 3
          struct body

          double p[3];//position
          double v[3];//velocity
          double a[3];//acceleration
          double radius;
          double mass;
          ;

          struct body bodies[n];

          int main()

          int a, b;
          for(a = 0; a < n; a++)

          for(b = 0; b < 3; b++)

          bodies[a].p[b] = 0;
          bodies[a].v[b] = 0;
          bodies[a].a[b] = 0;

          bodies[a].mass = 0;
          bodies[a].radius = 1.0;


          return 0;



          this works fine. your question was not very clear by the way, so match the layout of your source code with the above.






          share|improve this answer

























          • Also, I have a question about the placement between the declaration of the struct type and then actually making an instance of it - I have a different struct, one that I defined the contents of below where I first make an instance of it (just one this time, not an array), so why didn't this make the massive series of errors? It worked just fine, which led me to think that my attempt at making an array should have worked as well, but this time it didn't work. Also, thank you for your answer, it worked.

            – Amndeep7
            May 6 '12 at 15:07











          • Thanks!!!, this really help me!

            – FlokiTheFisherman
            Jul 24 '16 at 0:53






          • 1





            Hi, .... 59 likes ? I didn't see arrays of struct, I only see arrays of variable from struck...

            – delive
            Mar 15 '17 at 23:10














          90












          90








          90







          #include<stdio.h>
          #define n 3
          struct body

          double p[3];//position
          double v[3];//velocity
          double a[3];//acceleration
          double radius;
          double mass;
          ;

          struct body bodies[n];

          int main()

          int a, b;
          for(a = 0; a < n; a++)

          for(b = 0; b < 3; b++)

          bodies[a].p[b] = 0;
          bodies[a].v[b] = 0;
          bodies[a].a[b] = 0;

          bodies[a].mass = 0;
          bodies[a].radius = 1.0;


          return 0;



          this works fine. your question was not very clear by the way, so match the layout of your source code with the above.






          share|improve this answer















          #include<stdio.h>
          #define n 3
          struct body

          double p[3];//position
          double v[3];//velocity
          double a[3];//acceleration
          double radius;
          double mass;
          ;

          struct body bodies[n];

          int main()

          int a, b;
          for(a = 0; a < n; a++)

          for(b = 0; b < 3; b++)

          bodies[a].p[b] = 0;
          bodies[a].v[b] = 0;
          bodies[a].a[b] = 0;

          bodies[a].mass = 0;
          bodies[a].radius = 1.0;


          return 0;



          this works fine. your question was not very clear by the way, so match the layout of your source code with the above.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Mar 13 '17 at 22:15









          Adam Matthew

          365




          365










          answered May 6 '12 at 4:47









          nimsnims

          2,6441926




          2,6441926












          • Also, I have a question about the placement between the declaration of the struct type and then actually making an instance of it - I have a different struct, one that I defined the contents of below where I first make an instance of it (just one this time, not an array), so why didn't this make the massive series of errors? It worked just fine, which led me to think that my attempt at making an array should have worked as well, but this time it didn't work. Also, thank you for your answer, it worked.

            – Amndeep7
            May 6 '12 at 15:07











          • Thanks!!!, this really help me!

            – FlokiTheFisherman
            Jul 24 '16 at 0:53






          • 1





            Hi, .... 59 likes ? I didn't see arrays of struct, I only see arrays of variable from struck...

            – delive
            Mar 15 '17 at 23:10


















          • Also, I have a question about the placement between the declaration of the struct type and then actually making an instance of it - I have a different struct, one that I defined the contents of below where I first make an instance of it (just one this time, not an array), so why didn't this make the massive series of errors? It worked just fine, which led me to think that my attempt at making an array should have worked as well, but this time it didn't work. Also, thank you for your answer, it worked.

            – Amndeep7
            May 6 '12 at 15:07











          • Thanks!!!, this really help me!

            – FlokiTheFisherman
            Jul 24 '16 at 0:53






          • 1





            Hi, .... 59 likes ? I didn't see arrays of struct, I only see arrays of variable from struck...

            – delive
            Mar 15 '17 at 23:10

















          Also, I have a question about the placement between the declaration of the struct type and then actually making an instance of it - I have a different struct, one that I defined the contents of below where I first make an instance of it (just one this time, not an array), so why didn't this make the massive series of errors? It worked just fine, which led me to think that my attempt at making an array should have worked as well, but this time it didn't work. Also, thank you for your answer, it worked.

          – Amndeep7
          May 6 '12 at 15:07





          Also, I have a question about the placement between the declaration of the struct type and then actually making an instance of it - I have a different struct, one that I defined the contents of below where I first make an instance of it (just one this time, not an array), so why didn't this make the massive series of errors? It worked just fine, which led me to think that my attempt at making an array should have worked as well, but this time it didn't work. Also, thank you for your answer, it worked.

          – Amndeep7
          May 6 '12 at 15:07













          Thanks!!!, this really help me!

          – FlokiTheFisherman
          Jul 24 '16 at 0:53





          Thanks!!!, this really help me!

          – FlokiTheFisherman
          Jul 24 '16 at 0:53




          1




          1





          Hi, .... 59 likes ? I didn't see arrays of struct, I only see arrays of variable from struck...

          – delive
          Mar 15 '17 at 23:10






          Hi, .... 59 likes ? I didn't see arrays of struct, I only see arrays of variable from struck...

          – delive
          Mar 15 '17 at 23:10














          10














          I think you could write it that way too. I am also a student so I understand your struggle. A bit late response but ok .



          #include<stdio.h>
          #define n 3

          struct
          double p[3];//position
          double v[3];//velocity
          double a[3];//acceleration
          double radius;
          double mass;
          bodies[n];





          share|improve this answer



























            10














            I think you could write it that way too. I am also a student so I understand your struggle. A bit late response but ok .



            #include<stdio.h>
            #define n 3

            struct
            double p[3];//position
            double v[3];//velocity
            double a[3];//acceleration
            double radius;
            double mass;
            bodies[n];





            share|improve this answer

























              10












              10








              10







              I think you could write it that way too. I am also a student so I understand your struggle. A bit late response but ok .



              #include<stdio.h>
              #define n 3

              struct
              double p[3];//position
              double v[3];//velocity
              double a[3];//acceleration
              double radius;
              double mass;
              bodies[n];





              share|improve this answer













              I think you could write it that way too. I am also a student so I understand your struggle. A bit late response but ok .



              #include<stdio.h>
              #define n 3

              struct
              double p[3];//position
              double v[3];//velocity
              double a[3];//acceleration
              double radius;
              double mass;
              bodies[n];






              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Jun 8 '15 at 18:48









              ChristakitosChristakitos

              11316




              11316





















                  8














                  move



                  struct body bodies[n];


                  to after



                  struct body

                  double p[3];//position
                  double v[3];//velocity
                  double a[3];//acceleration
                  double radius;
                  double mass;
                  ;


                  Rest all looks fine.






                  share|improve this answer



























                    8














                    move



                    struct body bodies[n];


                    to after



                    struct body

                    double p[3];//position
                    double v[3];//velocity
                    double a[3];//acceleration
                    double radius;
                    double mass;
                    ;


                    Rest all looks fine.






                    share|improve this answer

























                      8












                      8








                      8







                      move



                      struct body bodies[n];


                      to after



                      struct body

                      double p[3];//position
                      double v[3];//velocity
                      double a[3];//acceleration
                      double radius;
                      double mass;
                      ;


                      Rest all looks fine.






                      share|improve this answer













                      move



                      struct body bodies[n];


                      to after



                      struct body

                      double p[3];//position
                      double v[3];//velocity
                      double a[3];//acceleration
                      double radius;
                      double mass;
                      ;


                      Rest all looks fine.







                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered May 6 '12 at 4:41









                      vrk001vrk001

                      265129




                      265129





















                          8














                          So to put it all together by using malloc():



                          int main(int argc, char** argv) 
                          typedef struct
                          char* firstName;
                          char* lastName;
                          int day;
                          int month;
                          int year;

                          STUDENT;

                          int numStudents=3;
                          int x;
                          STUDENT* students = malloc(numStudents * sizeof *students);
                          for (x = 0; x < numStudents; x++)
                          students[x].firstName=(char*)malloc(sizeof(char*));
                          scanf("%s",students[x].firstName);
                          students[x].lastName=(char*)malloc(sizeof(char*));
                          scanf("%s",students[x].lastName);
                          scanf("%d",&students[x].day);
                          scanf("%d",&students[x].month);
                          scanf("%d",&students[x].year);


                          for (x = 0; x < numStudents; x++)
                          printf("first name: %s, surname: %s, day: %d, month: %d, year: %dn",students[x].firstName,students[x].lastName,students[x].day,students[x].month,students[x].year);

                          return (EXIT_SUCCESS);






                          share|improve this answer




















                          • 7





                            Should your malloc line have numStudents * sizeof(STUDENT)?

                            – Todd
                            Jul 24 '14 at 16:57











                          • @Todd It's better not to. sizeof *students is the same thing and it won't be wrong if STUDENT ever happens to change.

                            – trentcl
                            Mar 11 '16 at 18:18















                          8














                          So to put it all together by using malloc():



                          int main(int argc, char** argv) 
                          typedef struct
                          char* firstName;
                          char* lastName;
                          int day;
                          int month;
                          int year;

                          STUDENT;

                          int numStudents=3;
                          int x;
                          STUDENT* students = malloc(numStudents * sizeof *students);
                          for (x = 0; x < numStudents; x++)
                          students[x].firstName=(char*)malloc(sizeof(char*));
                          scanf("%s",students[x].firstName);
                          students[x].lastName=(char*)malloc(sizeof(char*));
                          scanf("%s",students[x].lastName);
                          scanf("%d",&students[x].day);
                          scanf("%d",&students[x].month);
                          scanf("%d",&students[x].year);


                          for (x = 0; x < numStudents; x++)
                          printf("first name: %s, surname: %s, day: %d, month: %d, year: %dn",students[x].firstName,students[x].lastName,students[x].day,students[x].month,students[x].year);

                          return (EXIT_SUCCESS);






                          share|improve this answer




















                          • 7





                            Should your malloc line have numStudents * sizeof(STUDENT)?

                            – Todd
                            Jul 24 '14 at 16:57











                          • @Todd It's better not to. sizeof *students is the same thing and it won't be wrong if STUDENT ever happens to change.

                            – trentcl
                            Mar 11 '16 at 18:18













                          8












                          8








                          8







                          So to put it all together by using malloc():



                          int main(int argc, char** argv) 
                          typedef struct
                          char* firstName;
                          char* lastName;
                          int day;
                          int month;
                          int year;

                          STUDENT;

                          int numStudents=3;
                          int x;
                          STUDENT* students = malloc(numStudents * sizeof *students);
                          for (x = 0; x < numStudents; x++)
                          students[x].firstName=(char*)malloc(sizeof(char*));
                          scanf("%s",students[x].firstName);
                          students[x].lastName=(char*)malloc(sizeof(char*));
                          scanf("%s",students[x].lastName);
                          scanf("%d",&students[x].day);
                          scanf("%d",&students[x].month);
                          scanf("%d",&students[x].year);


                          for (x = 0; x < numStudents; x++)
                          printf("first name: %s, surname: %s, day: %d, month: %d, year: %dn",students[x].firstName,students[x].lastName,students[x].day,students[x].month,students[x].year);

                          return (EXIT_SUCCESS);






                          share|improve this answer















                          So to put it all together by using malloc():



                          int main(int argc, char** argv) 
                          typedef struct
                          char* firstName;
                          char* lastName;
                          int day;
                          int month;
                          int year;

                          STUDENT;

                          int numStudents=3;
                          int x;
                          STUDENT* students = malloc(numStudents * sizeof *students);
                          for (x = 0; x < numStudents; x++)
                          students[x].firstName=(char*)malloc(sizeof(char*));
                          scanf("%s",students[x].firstName);
                          students[x].lastName=(char*)malloc(sizeof(char*));
                          scanf("%s",students[x].lastName);
                          scanf("%d",&students[x].day);
                          scanf("%d",&students[x].month);
                          scanf("%d",&students[x].year);


                          for (x = 0; x < numStudents; x++)
                          printf("first name: %s, surname: %s, day: %d, month: %d, year: %dn",students[x].firstName,students[x].lastName,students[x].day,students[x].month,students[x].year);

                          return (EXIT_SUCCESS);







                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited Sep 21 '17 at 4:57









                          Ryan

                          5010




                          5010










                          answered Jul 2 '14 at 22:20









                          DounchanDounchan

                          9117




                          9117







                          • 7





                            Should your malloc line have numStudents * sizeof(STUDENT)?

                            – Todd
                            Jul 24 '14 at 16:57











                          • @Todd It's better not to. sizeof *students is the same thing and it won't be wrong if STUDENT ever happens to change.

                            – trentcl
                            Mar 11 '16 at 18:18












                          • 7





                            Should your malloc line have numStudents * sizeof(STUDENT)?

                            – Todd
                            Jul 24 '14 at 16:57











                          • @Todd It's better not to. sizeof *students is the same thing and it won't be wrong if STUDENT ever happens to change.

                            – trentcl
                            Mar 11 '16 at 18:18







                          7




                          7





                          Should your malloc line have numStudents * sizeof(STUDENT)?

                          – Todd
                          Jul 24 '14 at 16:57





                          Should your malloc line have numStudents * sizeof(STUDENT)?

                          – Todd
                          Jul 24 '14 at 16:57













                          @Todd It's better not to. sizeof *students is the same thing and it won't be wrong if STUDENT ever happens to change.

                          – trentcl
                          Mar 11 '16 at 18:18





                          @Todd It's better not to. sizeof *students is the same thing and it won't be wrong if STUDENT ever happens to change.

                          – trentcl
                          Mar 11 '16 at 18:18











                          1














                          That error means that the compiler is not able to find the definition of the type of your struct before the declaration of the array of structs, since you're saying you have the definition of the struct in a header file and the error is in nbody.c then you should check if you're including correctly the header file.
                          Check your #include's and make sure the definition of the struct is done before declaring any variable of that type.






                          share|improve this answer























                          • i doubt OP means header as header file, as he wrote, "the line below is above the stuff above" before the struct array declaration which is in his nbody.c file. Lets wait for him to wake up and clear the doubt.

                            – nims
                            May 6 '12 at 4:52












                          • @nims is correct, by header I meant the area above the main statement.

                            – Amndeep7
                            May 6 '12 at 14:39















                          1














                          That error means that the compiler is not able to find the definition of the type of your struct before the declaration of the array of structs, since you're saying you have the definition of the struct in a header file and the error is in nbody.c then you should check if you're including correctly the header file.
                          Check your #include's and make sure the definition of the struct is done before declaring any variable of that type.






                          share|improve this answer























                          • i doubt OP means header as header file, as he wrote, "the line below is above the stuff above" before the struct array declaration which is in his nbody.c file. Lets wait for him to wake up and clear the doubt.

                            – nims
                            May 6 '12 at 4:52












                          • @nims is correct, by header I meant the area above the main statement.

                            – Amndeep7
                            May 6 '12 at 14:39













                          1












                          1








                          1







                          That error means that the compiler is not able to find the definition of the type of your struct before the declaration of the array of structs, since you're saying you have the definition of the struct in a header file and the error is in nbody.c then you should check if you're including correctly the header file.
                          Check your #include's and make sure the definition of the struct is done before declaring any variable of that type.






                          share|improve this answer













                          That error means that the compiler is not able to find the definition of the type of your struct before the declaration of the array of structs, since you're saying you have the definition of the struct in a header file and the error is in nbody.c then you should check if you're including correctly the header file.
                          Check your #include's and make sure the definition of the struct is done before declaring any variable of that type.







                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered May 6 '12 at 4:50









                          DavidDavid

                          2618




                          2618












                          • i doubt OP means header as header file, as he wrote, "the line below is above the stuff above" before the struct array declaration which is in his nbody.c file. Lets wait for him to wake up and clear the doubt.

                            – nims
                            May 6 '12 at 4:52












                          • @nims is correct, by header I meant the area above the main statement.

                            – Amndeep7
                            May 6 '12 at 14:39

















                          • i doubt OP means header as header file, as he wrote, "the line below is above the stuff above" before the struct array declaration which is in his nbody.c file. Lets wait for him to wake up and clear the doubt.

                            – nims
                            May 6 '12 at 4:52












                          • @nims is correct, by header I meant the area above the main statement.

                            – Amndeep7
                            May 6 '12 at 14:39
















                          i doubt OP means header as header file, as he wrote, "the line below is above the stuff above" before the struct array declaration which is in his nbody.c file. Lets wait for him to wake up and clear the doubt.

                          – nims
                          May 6 '12 at 4:52






                          i doubt OP means header as header file, as he wrote, "the line below is above the stuff above" before the struct array declaration which is in his nbody.c file. Lets wait for him to wake up and clear the doubt.

                          – nims
                          May 6 '12 at 4:52














                          @nims is correct, by header I meant the area above the main statement.

                          – Amndeep7
                          May 6 '12 at 14:39





                          @nims is correct, by header I meant the area above the main statement.

                          – Amndeep7
                          May 6 '12 at 14:39











                          0














                          Solution using pointers:



                          #include<stdio.h>
                          #include<stdlib.h>
                          #define n 3
                          struct body

                          double p[3];//position
                          double v[3];//velocity
                          double a[3];//acceleration
                          double radius;
                          double *mass;
                          ;


                          int main()

                          struct body *bodies = (struct body*)malloc(n*sizeof(struct body));
                          int a, b;
                          for(a = 0; a < n; a++)

                          for(b = 0; b < 3; b++)

                          bodies[a].p[b] = 0;
                          bodies[a].v[b] = 0;
                          bodies[a].a[b] = 0;

                          bodies[a].mass = 0;
                          bodies[a].radius = 1.0;


                          return 0;






                          share|improve this answer



























                            0














                            Solution using pointers:



                            #include<stdio.h>
                            #include<stdlib.h>
                            #define n 3
                            struct body

                            double p[3];//position
                            double v[3];//velocity
                            double a[3];//acceleration
                            double radius;
                            double *mass;
                            ;


                            int main()

                            struct body *bodies = (struct body*)malloc(n*sizeof(struct body));
                            int a, b;
                            for(a = 0; a < n; a++)

                            for(b = 0; b < 3; b++)

                            bodies[a].p[b] = 0;
                            bodies[a].v[b] = 0;
                            bodies[a].a[b] = 0;

                            bodies[a].mass = 0;
                            bodies[a].radius = 1.0;


                            return 0;






                            share|improve this answer

























                              0












                              0








                              0







                              Solution using pointers:



                              #include<stdio.h>
                              #include<stdlib.h>
                              #define n 3
                              struct body

                              double p[3];//position
                              double v[3];//velocity
                              double a[3];//acceleration
                              double radius;
                              double *mass;
                              ;


                              int main()

                              struct body *bodies = (struct body*)malloc(n*sizeof(struct body));
                              int a, b;
                              for(a = 0; a < n; a++)

                              for(b = 0; b < 3; b++)

                              bodies[a].p[b] = 0;
                              bodies[a].v[b] = 0;
                              bodies[a].a[b] = 0;

                              bodies[a].mass = 0;
                              bodies[a].radius = 1.0;


                              return 0;






                              share|improve this answer













                              Solution using pointers:



                              #include<stdio.h>
                              #include<stdlib.h>
                              #define n 3
                              struct body

                              double p[3];//position
                              double v[3];//velocity
                              double a[3];//acceleration
                              double radius;
                              double *mass;
                              ;


                              int main()

                              struct body *bodies = (struct body*)malloc(n*sizeof(struct body));
                              int a, b;
                              for(a = 0; a < n; a++)

                              for(b = 0; b < 3; b++)

                              bodies[a].p[b] = 0;
                              bodies[a].v[b] = 0;
                              bodies[a].a[b] = 0;

                              bodies[a].mass = 0;
                              bodies[a].radius = 1.0;


                              return 0;







                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered Oct 16 '18 at 17:21









                              Helping BeanHelping Bean

                              1467




                              1467





















                                  0














                                  Another way of initializing an array of structs is to initialize the array members explicitly. This approach is useful and simple if there aren't too many struct and array members.



                                  Use the typedef specifier to avoid re-using the struct statement everytime you declare a struct variable:



                                  typedef struct

                                  double p[3];//position
                                  double v[3];//velocity
                                  double a[3];//acceleration
                                  double radius;
                                  double mass;
                                  Body;


                                  Then declare your array of structs. Initialization of each element goes along with the declaration:



                                  Body bodies[n] = 0,0,0, 0,0,0, 0,0,0, 0, 1.0, 
                                  0,0,0, 0,0,0, 0,0,0, 0, 1.0,
                                  0,0,0, 0,0,0, 0,0,0, 0, 1.0;


                                  To repeat, this is a rather simple and straightforward solution if you don't have too many array elements and large struct members and if you, as you stated, are not interested in a more dynamic approach. This approach can also be useful if the struct members are initialized with named enum-variables (and not just numbers like the example above) whereby it gives the code-reader a better overview of the purpose and function of a structure and its members in certain applications.






                                  share|improve this answer



























                                    0














                                    Another way of initializing an array of structs is to initialize the array members explicitly. This approach is useful and simple if there aren't too many struct and array members.



                                    Use the typedef specifier to avoid re-using the struct statement everytime you declare a struct variable:



                                    typedef struct

                                    double p[3];//position
                                    double v[3];//velocity
                                    double a[3];//acceleration
                                    double radius;
                                    double mass;
                                    Body;


                                    Then declare your array of structs. Initialization of each element goes along with the declaration:



                                    Body bodies[n] = 0,0,0, 0,0,0, 0,0,0, 0, 1.0, 
                                    0,0,0, 0,0,0, 0,0,0, 0, 1.0,
                                    0,0,0, 0,0,0, 0,0,0, 0, 1.0;


                                    To repeat, this is a rather simple and straightforward solution if you don't have too many array elements and large struct members and if you, as you stated, are not interested in a more dynamic approach. This approach can also be useful if the struct members are initialized with named enum-variables (and not just numbers like the example above) whereby it gives the code-reader a better overview of the purpose and function of a structure and its members in certain applications.






                                    share|improve this answer

























                                      0












                                      0








                                      0







                                      Another way of initializing an array of structs is to initialize the array members explicitly. This approach is useful and simple if there aren't too many struct and array members.



                                      Use the typedef specifier to avoid re-using the struct statement everytime you declare a struct variable:



                                      typedef struct

                                      double p[3];//position
                                      double v[3];//velocity
                                      double a[3];//acceleration
                                      double radius;
                                      double mass;
                                      Body;


                                      Then declare your array of structs. Initialization of each element goes along with the declaration:



                                      Body bodies[n] = 0,0,0, 0,0,0, 0,0,0, 0, 1.0, 
                                      0,0,0, 0,0,0, 0,0,0, 0, 1.0,
                                      0,0,0, 0,0,0, 0,0,0, 0, 1.0;


                                      To repeat, this is a rather simple and straightforward solution if you don't have too many array elements and large struct members and if you, as you stated, are not interested in a more dynamic approach. This approach can also be useful if the struct members are initialized with named enum-variables (and not just numbers like the example above) whereby it gives the code-reader a better overview of the purpose and function of a structure and its members in certain applications.






                                      share|improve this answer













                                      Another way of initializing an array of structs is to initialize the array members explicitly. This approach is useful and simple if there aren't too many struct and array members.



                                      Use the typedef specifier to avoid re-using the struct statement everytime you declare a struct variable:



                                      typedef struct

                                      double p[3];//position
                                      double v[3];//velocity
                                      double a[3];//acceleration
                                      double radius;
                                      double mass;
                                      Body;


                                      Then declare your array of structs. Initialization of each element goes along with the declaration:



                                      Body bodies[n] = 0,0,0, 0,0,0, 0,0,0, 0, 1.0, 
                                      0,0,0, 0,0,0, 0,0,0, 0, 1.0,
                                      0,0,0, 0,0,0, 0,0,0, 0, 1.0;


                                      To repeat, this is a rather simple and straightforward solution if you don't have too many array elements and large struct members and if you, as you stated, are not interested in a more dynamic approach. This approach can also be useful if the struct members are initialized with named enum-variables (and not just numbers like the example above) whereby it gives the code-reader a better overview of the purpose and function of a structure and its members in certain applications.







                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered Jan 14 at 10:40









                                      Abdel AleemAbdel Aleem

                                      356




                                      356



























                                          draft saved

                                          draft discarded
















































                                          Thanks for contributing an answer to Stack Overflow!


                                          • Please be sure to answer the question. Provide details and share your research!

                                          But avoid


                                          • Asking for help, clarification, or responding to other answers.

                                          • Making statements based on opinion; back them up with references or personal experience.

                                          To learn more, see our tips on writing great answers.




                                          draft saved


                                          draft discarded














                                          StackExchange.ready(
                                          function ()
                                          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f10468128%2fhow-do-you-make-an-array-of-structs-in-c%23new-answer', 'question_page');

                                          );

                                          Post as a guest















                                          Required, but never shown





















































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown

































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown







                                          Popular posts from this blog

                                          Save data to MySQL database using ExtJS and PHP [closed]2019 Community Moderator ElectionHow can I prevent SQL injection in PHP?Which MySQL data type to use for storing boolean valuesPHP: Delete an element from an arrayHow do I connect to a MySQL Database in Python?Should I use the datetime or timestamp data type in MySQL?How to get a list of MySQL user accountsHow Do You Parse and Process HTML/XML in PHP?Reference — What does this symbol mean in PHP?How does PHP 'foreach' actually work?Why shouldn't I use mysql_* functions in PHP?

                                          Compiling GNU Global with universal-ctags support Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!Tags for Emacs: Relationship between etags, ebrowse, cscope, GNU Global and exuberant ctagsVim and Ctags tips and trickscscope or ctags why choose one over the other?scons and ctagsctags cannot open option file “.ctags”Adding tag scopes in universal-ctagsShould I use Universal-ctags?Universal ctags on WindowsHow do I install GNU Global with universal ctags support using Homebrew?Universal ctags with emacsHow to highlight ctags generated by Universal Ctags in Vim?

                                          Add ONERROR event to image from jsp tldHow to add an image to a JPanel?Saving image from PHP URLHTML img scalingCheck if an image is loaded (no errors) with jQueryHow to force an <img> to take up width, even if the image is not loadedHow do I populate hidden form field with a value set in Spring ControllerStyling Raw elements Generated from JSP tagds with Jquery MobileLimit resizing of images with explicitly set width and height attributeserror TLD use in a jsp fileJsp tld files cannot be resolved