Menu
Coddy logo textTech

Access Members

Lesson 3 of 8 in Coddy's C/C++ Structures course.

To initialize a structure named Person, use:

Person p1;

Now, you have a variable named p1 of type Person.

In C, you also need to add the struct keyword before:

struct Person p1;

To access the members of the structure, use the dot syntax (.):

p1.age = 26;
p1.name = "bob";

cout << "Age: " << p1.age << endl;
cout << "Name: " << p1.name << endl;

The above will set values for the two members age and name and print them.

In C, you will need to use the string.h library to set string values like this:

p1.age = 26;
strcpy(p1.name, "bob");

printf("Age: %d\n", p1.age);
printf("Name: %c\n", p1.name);
challenge icon

Challenge

Easy

You are given a structure named Person and some code.

Initialize two variables named bob and john of this structure and modify the members values to match the expected output.

Try it yourself

#include <stdio.h>
#include <string.h>

struct person {
    char fullName[30];
    char country[10];
    int age;
};

int main() {
    // Write code here

    // Don't change below this line
    printf("--- bob ---\n");
    printf("Name: %s\n", bob.fullName);
    printf("Country: %s\n", bob.country);
    printf("Age: %d\n\n", bob.age);
    printf("--- john ---\n");
    printf("Name: %s\n", john.fullName);
    printf("Country: %s\n", john.country);
    printf("Age: %d\n", john.age);
    return 0;
};

All lessons in C/C++ Structures