CodeBlanks Logo Icon CodeBlanks

Using structs

Learn to declare struct variables and access fields.

struct variable and member access

After defining a struct you can create variables. To access members you use the . operator.

struct Point p;
p.x = 5;
p.y = 10;

Here p is a struct Point variable. With p.x you reach the x member and can assign a value. You can also initialize with {5, 10} at definition. You can also modify members one by one.

Initialization styles

You can give a struct variable its value at definition or later. Initialization uses curly braces.

struct Point a = {1, 2};
struct Point b;
b.x = 3;
b.y = 4;
struct Point c = a;

Here a takes its value at definition; b is declared first then its members are assigned one by one; c becomes a copy of a. All three are valid; you choose one depending on the situation. Member access is always with ..

Practice Assign members and sum

Declare struct Point p. Assign p.x = 5 and p.y = 10. Print the sum p.x + p.y with printf.

Starter code

main.c
#include <stdio.h>

struct Point { int x; int y; };

int main(void) {
    /* Declare a Point variable; assign x=5, y=10; print the sum with printf */
    return 0;
}

Sample solution

main.c
struct Point p;
p.x = 5;
p.y = 10;
printf("%d\n", p.x + p.y);

Expected output

15

Questions and answers

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

1 Match declaration to meaning

Term Meaning
struct Point p; Variable declaration
p.x = 5; Member assignment
{3, 4} Initial value
p.x Member access

2 Which operator is used to access a struct member?

  • ->
  • *
  • ::
  • . Correct answer

Explanation: Member access on a struct variable uses .

3 Fill in the blank: member access

Question
struct Point p;
p____ = 5;
Answer
struct Point p;
p.x = 5;

Explanation: p.x accesses the x member.

All lessons in Beginner