CodeBlanks Logo Icon CodeBlanks

Defining structs

Learn to define a struct that combines multiple fields.

struct: grouping data

A struct groups data of different types under one roof. It starts with the struct keyword and members go inside curly braces.

struct Point {
    int x;
    int y;
};

Here struct Point is a type with two int members. The semicolon at the end is mandatory. This is the basic tool to manage two coordinates of a point together. The same approach can model many real objects like student, book or product.

Defining members

Struct members are written inside curly braces like normal variable declarations. Each member has its own type and name.

struct Book {
    char title[64];
    int year;
    double price;
};

Here title is a string, year is an integer, price is a double. Member names must be unique within the same struct. To access a member you use the . operator; we will see this in the next lesson.

Practice Define struct Point and print

Define struct Point with int x and int y members. In main create a Point variable with {3, 4} and print x and y with printf.

Starter code

main.c
#include <stdio.h>

/* Define struct Point with int x and int y */
int main(void) {
    /* Create a Point and print it with printf */
    return 0;
}

Sample solution

main.c
struct Point { int x; int y; };
struct Point p = {3, 4};
printf("%d %d\n", p.x, p.y);

Expected output

3 4

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which keyword is used to declare a struct?

  • type
  • class
  • struct Correct answer
  • record

Explanation: In C the struct keyword declares a struct.

2 Fill in the blank: struct definition

Question
struct Point {
    int x;
    int ____;
};
Answer
struct Point {
    int x;
    int y;
};

Explanation: The second member of Point is y.

3 Match concept to explanation

Term Meaning
struct Struct keyword
member Variable inside struct
{ } Surrounds members
; Ends definition

All lessons in Beginner