Use:

#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.

Answer from nims on Stack Overflow
Top answer
1 of 10
149

Use:

#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.

2 of 10
28

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.

๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ c language โ€บ c-array-of-structure
Array of Structures in C - GeeksforGeeks
So, if we declare the variable this way, it's not possible to handle this. struct Employee emp1, emp2, emp3, .. . ... . .. ... emp1000; For that, we can define an array whose data type will be struct Employee soo that will be easily manageable.
Published ย  October 21, 2025
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ c language โ€บ how-to-create-an-array-of-structs-in-c
How to Create an Array of Structs in C? - GeeksforGeeks
July 23, 2025 - To create an array of structs, we first need to define the struct type and then declare an array of that type using the below syntax.
๐ŸŒ
Reddit
reddit.com โ€บ r/c_programming โ€บ can someone explain how does array of structures work?
r/C_Programming on Reddit: Can someone explain how does array of structures work?
January 15, 2023 -

Good day,

So I created a structure Position with two int members.

struct Position {
    int x;
    int y;
};

typedef struct Position Position;

int main() {
    Position *current = (Position*)malloc(sizeof(Position));
    ...
}

If I want to create an array of it, should I just multiply it to how many elements I want to use?Does pointer arithmetic will move me to the next element struct every time I add 1 to the pointer?Why when I try to reallocate it by multiplying to higher number, it returns invalid pointer even though I just passed the pointer coming from malloc(). Thanks for answering and have a nice day.

๐ŸŒ
Reddit
reddit.com โ€บ r/cprogramming โ€บ structure contining an array of structures - how to initialise?
r/cprogramming on Reddit: structure contining an array of structures - how to initialise?
March 9, 2023 -

Hi all - bit of help needed. I have two structs in C++.
The first structure needs to contain an array of the second type, but I cannot work out how to initialise this.

typedef struct
{
String something;
int somethingElse;
} harryType;
typedef struct
{
String Name;
harryType harrys[ ];
} fredType;

fredType freds[]={"bill",{"blah",3}, {"bleg",10}, "george", {"yuck",4}, {"meh",7} };

is what I tried - but it doesnt like the harrys[ ].

What is the solution please? I guess the memory needs allocating dynamically? Perhaps a list?

Cheers, Jim

๐ŸŒ
Linux Hint
linuxhint.com โ€บ make-array-structs-c
How to Make an Array of Structs in C โ€“ Linux Hint
Above program defines the pointer to object of structure. Malloc function is used to allocate memory for the pointer variable. We initialize the member variables with specific values and print those variables by accessing the members with pointer. a is assigned with 4, b is assigned with โ€˜dโ€™ and c is assigned with float value 5.5. Below is the snapshot of the program and output. ... Now, let us go through the C program for array of structures and array of pointers to structures.
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ cprogramming โ€บ c_arrays_of_structures.htm
Array of Structures in C
An array of three struct student types is declared and the first four elements are populated by user input, with a for loop. Inside the loop itself, the "percent" element of each subscript is computed.
๐ŸŒ
Delft Stack
delftstack.com โ€บ home โ€บ howto โ€บ c array of structs
How to Create Array of Structs in C | Delft Stack
February 12, 2024 - The code begins by including the standard input/output library (stdio.h). Next, a structure named Student is defined, containing three members: rollNumber (integer), studentName (character array of size 20), and percentage (float).
Find elsewhere
๐ŸŒ
Ycpcs
ycpcs.github.io โ€บ cs101-fall2023 โ€บ lectures โ€บ lecture19.html
CS 101: Lecture 19: Arrays of structs (with functions)
Since a struct type is simply a user-defined datatype, they can be used in the declaration of an array. For example, given the following basic structure declaration ... We can declare an array of Pointโ€™s similarly to how we have declared other primitive data type arrays (assuming NUM_POINTS ...
๐ŸŒ
OverIQ
overiq.com โ€บ c-programming-101 โ€บ array-of-structures-in-c
Array of Structures in C - C Programming Tutorial - OverIQ.com
In line 14, we have declared an array of structures of type struct student whose size is controlled by symbolic constant MAX. If you want to increase/decrease the size of the array just change the value of the symbolic constant and our program will adapt to the new size.
๐ŸŒ
w3tutorials
w3tutorials.net โ€บ blog โ€บ how-do-you-make-an-array-of-structs-in-c
How to Make an Array of Structs in C: Step-by-Step Guide for Celestial Bodies (Avoid Common Errors) โ€” w3tutorials.net
This guide will walk you through creating an array of structs in C, using celestial bodies as a practical example. Weโ€™ll cover struct definition, array declaration, initialization, access, and common pitfalls to avoid.
๐ŸŒ
Scaler
scaler.com โ€บ home โ€บ topics โ€บ array of structure in c
Array of Structure in C - Scaler Topics
April 3, 2024 - Hence, C enables us to declare an array of structures. We can evade declaring the different structure variables; instead, we can make an array containing all the structures that store the data of separate entities.
๐ŸŒ
Quora
quora.com โ€บ How-can-I-make-an-array-of-pointers-to-structs-in-c
How to make an array of pointers to structs in c - Quora
Summary: declare Item arr[N] or Item *arr with malloc, allocate or assign each element to point at a struct (separately allocated, statically allocated, or inside a contiguous block), manage memory carefully, and prefer contiguous blocks if ...
๐ŸŒ
Quora
quora.com โ€บ How-do-you-initialize-an-array-of-structures-in-C
How to initialize an array of structures in C - Quora
Since a struct can be initialized using {} notation and an array as well, you may assign all array elements comma-delimited bracketed with curly braces. Each element being a struct can also be initialized to the field values comma-delimited ...
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ explain-the-array-of-structures-in-c-language
Explain the array of structures in C language
December 6, 2024 - An array of three struct student types is declared and the first four elements are populated by user input, with a for loop. Inside the loop itself, the "percent" element of each subscript is computed.
๐ŸŒ
Reddit
reddit.com โ€บ r/learnprogramming โ€บ how can i create an array of structs in c? it appears changing one element in in array changes all of them
r/learnprogramming on Reddit: How can I create an array of structs in C? It appears changing one element in in array changes all of them
January 30, 2014 -

Hello,

First of all, please don't tell me to search. I have searched and none of the answers have been able to help me solve my problem.

I am trying to make an array of structs. Here's my code:

#include <stdio.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>

struct NameValue {
	char *name;
	char *value;
};

    void myfuction(){
            int numvals; //the # of positions in the array
            //code here that calculates and sets numvals
            struct NameValue *NameValuearray = (struct NameValue*)calloc(numvals,sizeof(*NameValuearray));

            int structpos;
            char tempname[300];
            char tempvalue[300];
            for(structpos = 0; structpos < numvals; structpos++){
                    //code here that sets tempname and tempvalue. This is different every iteration
                    struct NameValue thisnamevalue;
                    thisnamevalue.name = tempname;
                    thisnamevalue.value = tempvalue;

                    NameValuearray[structpos] = thisnamevalue;
                    struct NameValue asdf = NameValuearray[0];
            }
    }

I have verified that at the end of each iteration of the for loop, thisnamevalue does contain the correct information. I want the array to hold a copy of thisnamevalue after every iteration. So NameValuearray[0] contains thisnamevalue as it was at the end of the first iteration, NameValuearray[1] contains thisnamevalue as it was at the end of the second iteration, and so on. In this functionality, once NameValuearray[0] is set, it is not changed.

		struct NameValue asdf = NameValuearray[0];
		printf("%s\n", asdf.name);

^ This code should then print the same thing numval times. Instead, each time it runs, it prints the 'name' of thisnamevalue as it was when it was last placed in the array. So running

NameValuearray[3] = thisnmevalue

should not change what the abouve two lines of code print, but it does. Does anybody know how to fix this?

Top answer
1 of 1
5
struct NameValue { char *name; char *value; }; This does not actually store any strings. It only contains pointers to char, which are a numeric type. In C, there is not really any string type. Instead, we have a few conventions: The numbers stored in a char shall be interpreted as characters of text, as long as they have values between 0 and 127 inclusive, mapped according to the ASCII standard; A sequence of consecutive char-sized blocks of memory, ending with a zero value, can be interpreted as a sequence of characters, which we will pretend is a "string"; In source code, text between double quotes (a "string literal") shall be converted into such a sequence of char values when represented in memory, with a zero value ("null terminator") automatically appended; A bunch of library functions are defined such that, when supplied with a pointer to char, they blindly assume that it points at the beginning of such a "string". Everything else that happens is a consequence of pointers and arrays behaving the same way that they would no matter what kind of thing they are pointing at. When you create the local char tempname[300] and char tempvalue[300] arrays, they are exactly what they sound like - temporary. When you make assignments like thisnamevalue.name = tempname, you are copying a pointer value - the pointer within the struct now points at the memory temporarily allocated on the stack. Every struct in your allocated NameValuearray points at the same arrays; and at the end of the function, they are now invalid, because the arrays have ceased to exist. Attempting to access them will then be undefined behaviour. Your options are: include an actual array in the struct instead of a pointer (and deal with the fact that you're now stuck with that maximum size for the text, and that every instance will use the maximum amount of space); allocate memory for the pointers to point at (the same way that you had to allocate memory to hold the struct instances), and do all the associated ensuing memory management; (recommended) run away screaming, and adopt a language that actually provides proper support for simple concepts like "strings".
๐ŸŒ
Unstop
unstop.com โ€บ home โ€บ blog โ€บ array of structures in c language explained with examples
Array Of Structures In C Language Explained With Examples
July 19, 2024 - Inside the loop, we use the printf() function to print each memberโ€™s ID with a label like "Member 1 ID:", "Member 2 ID:", and so on. Finally, the main function returns 0, which signals that the program finished successfully. The array of structures in the C programming language is a powerful tool that offers a structured approach to organizing complex data types. It makes it easier to store, access, and manipulate information efficiently.
๐ŸŒ
Quora
quora.com โ€บ How-do-I-make-an-array-of-structures-inside-a-structure-in-C
How to make an array of structures inside a structure in C - Quora
Answer (1 of 2): You can easily do that but not of the SAME structure as a structure cannot self contain itself. (if it had where will it end?) so no is impossible to do that. Even so you can instead make an array of โ€œotherโ€ structure. and that is easy lets call inStr the array of structures ...
๐ŸŒ
All About Circuits
forum.allaboutcircuits.com โ€บ home โ€บ forums โ€บ embedded & programming โ€บ programming & languages
how to define struct array in c | All About Circuits
August 16, 2016 - Look at the material here for some ... me. Try this. ... typedef struct my_structure { some_field1; some_field2; some_field3; }; my_structure structure_array[50]; structure_array[2]->some_field2 = some_data;...