Coding

Struct in C: Define, Initialize and Use It (with Examples)

A struct in C groups several variables of different types into one named type. You define it with struct name { ... };, create a variable with struct name var = { ... };, and read members with var.member or ptr->member.

#include <stdio.h>

struct point {
    double x;
    double y;
};

int main(void)
{
    struct point origin = { .x = 0.0, .y = 0.0 };
    struct point p = { 3.0, 4.0 };

    printf("p = (%.1f, %.1f)\n", p.x, p.y);
    printf("origin = (%.1f, %.1f)\n", origin.x, origin.y);
    return 0;
}

Example output:

p = (3.0, 4.0)
origin = (0.0, 0.0)

How to define a struct in C

A struct declaration lists the members inside braces. The list can hold ordinary variable declarations and bit-field declarations. The members are laid out in memory in the order you declare them.

struct student {
    char name[32];
    int year;
    double average;
};

The type is now called struct student, and you must write the word struct every time you use it. That is how C keeps struct tags in their own namespace. If you would rather write just student, add a typedef:

typedef struct student {
    char name[32];
    int year;
    double average;
} student;

student first;   /* same type as struct student */

Keeping the tag (struct student) in a typedef is useful when the struct refers to itself, as in the linked list below. A struct cannot contain a member of its own type, because its size would be infinite. It can contain a pointer to its own type, and that is how linked lists and trees are built.

struct node {
    int value;
    struct node *next;
};

The members you list must be of complete type. The one exception is a flexible array member as the last member, covered near the end of this article.

How to initialize a struct in C

There are three common ways. All of them give the same result for the members you mention. The difference is readability and how safe the code is when someone later adds or reorders members.

Positional initializers

struct student s = { "Ada", 2, 9.1 };

The first value goes to the first member, the second to the second, and so on. This breaks quietly if the member order changes, so use it only for small, stable structs such as a point.

Designated initializers (C99 and later)

struct student s = { .name = "Ada", .average = 9.1, .year = 2 };

Each .member = value names its target, so the order does not matter and the code stays correct when members are added. Per cppreference, initialization continues forward in declaration order after a designator, so a value without a designator fills the member declared after the previous one.

Zero or partial initialization

Members you leave out of the braces are initialized as if by an empty initializer, which means zero for numbers and a null pointer for pointers:

struct point p = { 1.2, 1.3 };   /* p.x = 1.2, p.y = 1.3 */
struct student blank = { 0 };    /* every member is zero */

This is the important difference from an uninitialized variable. A struct with automatic storage (a local variable) declared as struct student s; holds indeterminate values until you assign them. Reading them is a bug. Writing = { 0 } is the usual way to start from a known state. Before C23 an empty {} was an error in standard C, so { 0 } is the portable spelling. Giving more initializers than there are members is also an error.

One rule applies to globals and static variables: every expression in their initializer list must be a constant expression. A call such as malloc(1) in a static struct's initializer is rejected. Local structs can use any expression.

Compound literals

A compound literal builds an unnamed struct value in place. The C standard defines it in section 6.5.2.5, and it follows the same initialization rules:

struct point *pp = &(struct point){ .x = 1.0 };   /* y is 0.0 */

In a function, the object has automatic storage, so the pointer is valid only until the enclosing block ends. Do not return it.

How to access struct members: . and ->

Use the dot operator on a struct object and the arrow operator on a pointer to a struct. Per cppreference, a.b accesses member b of the struct a, and a->b accesses member b of the struct that a points to. The arrow form is the same as (*a).b.

struct point p = { 3.0, 4.0 };
struct point *ptr = &p;

ptr->x = 7.0;      /* through the pointer */
(*ptr).y = 8.0;    /* same thing, written longer */
printf("%.1f %.1f\n", p.x, p.y);

Example output:

7.0 8.0

The parentheses in (*ptr).y are required. The dot binds tighter than the unary *, so *ptr.y means *(ptr.y), which does not compile because ptr is a pointer and has no member y. Write ptr->y and the problem disappears. If pointers are still new to you, pointers in C explained with examples covers the basics.

Passing a struct to a function

C passes arguments by value, and a struct is no exception. When you pass a struct, the function receives a copy of every member. Changes inside the function do not affect the caller's struct.

struct point move_right(struct point p, double dx)
{
    p.x += dx;      /* modifies the copy */
    return p;       /* returning a struct copies it back */
}

void move_right_in_place(struct point *p, double dx)
{
    p->x += dx;     /* modifies the caller's struct */
}

For small structs the copy is fine. For large ones, pass a pointer. Add const when the function only reads the data: double length(const struct point *p). The compiler then rejects any write through p.

Assignment works the same way: struct point b = a; copies all members of a. A fixed-size array member, such as char name[32], is copied along with it. A pointer member is copied as an address, so both structs end up pointing at the same memory. That is a shallow copy, and you must decide who owns and frees the pointed-to memory.

Arrays of structs and dynamic allocation

A struct type can be an array element, so a table of records is just an array:

struct point path[3] = {
    { 0.0, 0.0 },
    { 1.0, 2.0 },
    { 3.0, 4.0 }
};

for (int i = 0; i < 3; i++) {
    printf("%.1f %.1f\n", path[i].x, path[i].y);
}

For the array rules, see arrays in C. To create a struct on the heap, allocate with the type's size and check the result. Using sizeof *node keeps the size correct even if you later change the pointer's type:

struct node *node = malloc(sizeof *node);
if (node == NULL) {
    return NULL;
}
node->value = 42;
node->next = NULL;

Release it with free(node) when you are done. malloc in C goes through the failure cases and leak patterns.

Why sizeof a struct can be bigger than its members

The C standard allows unnamed padding between any two members and after the last one, but never before the first. The size of a struct is at least the sum of the sizes of its members, and often more. Member order changes how much padding you get. The cppreference page shows this pair, with offsets from a typical 64-bit platform:

struct A { char a; double b; char c; };   /* offsets 0, 8, 16; sizeof 24 */
struct B { char a; char b; double c; };   /* offsets 0, 1, 8;  sizeof 16 */

Both hold the same three members, yet struct A is 8 bytes larger. These numbers assume double needs 8-byte alignment, which is common but not guaranteed by the language. Check on your own compiler with printf("%zu\n", sizeof(struct A));. Because padding contents are unspecified, do not write a struct to a file or a network socket with a single fwrite if the data must be read on another platform.

Comparing structs

The == and != operators do not work on structs. Compare the members you care about:

int point_equal(struct point a, struct point b)
{
    return a.x == b.x && a.y == b.y;
}

Calling memcmp on two structs looks shorter, but it also compares padding bytes, which can differ even when every member matches. Compare member by member unless you know the struct has no padding and no floating-point members.

Flexible array members

If a struct has at least one named member, its last member may be declared as an array with no size. This is a flexible array member. You allocate the struct together with the extra space it needs:

struct buffer {
    size_t length;
    double values[];
};

struct buffer *buf = malloc(sizeof *buf + 8 * sizeof buf->values[0]);

This gives room for eight doubles. Three rules from cppreference matter in practice. sizeof omits the flexible member, though it may include trailing padding. Initialization and assignment ignore the flexible member, so *s1 = *s2 does not copy the array elements. And a struct with a flexible array member cannot be an array element or a member of another struct.

Common mistakes

  • Forgetting the semicolon after the closing brace. struct point { ... } must end with ;. Without it the compiler reports an error on the next line, not on the struct.
  • Using a local struct uninitialized. Members hold indeterminate values. Start with = { 0 }.
  • Using . on a pointer or -> on an object. Match the operator to what you have.
  • Returning a pointer to a local struct. The object is gone when the function returns. Return the struct by value or allocate it on the heap.
  • Assuming a copy duplicates heap data. Pointer members are shared after assignment.

Frequently asked questions

What is a struct in C?
A struct is a user-defined type that groups several named variables, called members, into one object. The members can have different types, and they are stored in the order you declare them. You read and write a member with the dot operator, or with the arrow operator when you have a pointer to the struct.
What is the difference between . and -> in C?
The dot operator (s.x) accesses a member of a struct object. The arrow operator (p->x) accesses a member of the struct that a pointer points to, and it is equivalent to (*p).x. Using the dot on a pointer, or the arrow on a plain struct, is a compile error.
Can you compare two structs with == in C?
No. The == and != operators do not work on struct operands, so the compiler rejects them. Compare the members one by one. Using memcmp on the whole struct is risky, because padding bytes between members can hold indeterminate values.
Does assigning one struct to another copy it?
Yes. Assigning a struct of the same type copies every member, including members that are arrays of fixed size. Pointer members are copied as pointer values, so both structs then point at the same memory, which is a shallow copy.
Why is sizeof a struct bigger than the sum of its members?
The compiler may insert unnamed padding between members and after the last one so that each member sits at a suitable address. The C standard only guarantees that the size is at least the sum of the member sizes. Ordering members from largest to smallest often reduces the padding.

Sources