What is Accessing Structure Members in C- Embedded C Programming Course Online

🚀 Learn BLE on Linux (BlueZ) – Programming Part 1

Hands-on Bluetooth Low Energy course. Special price: ₹399

Enroll Now on Udemy →
💬 Need help or career guidance? Ask us!Contact Us →

Free C Programming Course · Chapter 10 · Lecture 4

Accessing Structure Members in C

Master the dot operator: read, write, scan and copy structure members, and avoid the mistakes that trip up every beginner.

Defining, declaring and initializing structures is only the setup. The real work of embedded C programming happens when you read a sensor value into a member, update a status field, or compare two records. In this lecture of our free C programming course you will learn how to access structure members in C with the dot operator and how to handle the special cases: strings, scanf, whole-structure copies and comparisons.

Everything on this free C tutorial page was compiled and executed, including the error messages. By the end you will be able to write a complete program that fills, prints and compares structure variables.

What You Will Learn

You will be able to:

  • Use the dot (.) member access operator correctly.
  • Assign numbers directly and text with strcpy.
  • Read values from the keyboard straight into members with scanf.
  • Copy a whole structure, and explain why == cannot compare two structures.
  • Recognize and fix the two most common member-access compiler errors.

Prerequisites

Lectures 1 to 3 of this chapter, plus strcpy from the Strings chapter and scanf from the Input-Output chapter.

The Dot Operator

To reach one member of a structure variable, write the variable name, a dot, and the member name:

structvariable.member

The dot is called the member access operator (some books call it the period or membership operator). On its left there must be a structure variable; on its right there must be the name of a member of that variable’s structure type. The whole expression behaves exactly like an ordinary variable of the member’s type: you can read it, print it, assign to it, use it in arithmetic, take its address, or pass it to a function.

Reading the expression a.temp_c

a : the variable. : go insidetemp_c : the member
Result : a float you can use like any other float

With the sensor_node structure from Lecture 1 and the variables a and b, the accessible members are:

ExpressionTypeMeaning
a.labelchar[12]Text name of node a
a.node_idintID of node a
a.temp_cfloatTemperature of node a
b.temp_cfloatTemperature of node b; a separate copy

Each variable owns its own members. Changing a.temp_c never touches b.temp_c.

Assigning Values to Members

Numeric members are assigned with the plain = operator:

b.node_id = 8;
b.temp_c  = 45.25f;

A character-array member is different. An array name is not something you can assign to, so b.label = "pump"; is rejected. Copy the text in with strcpy (or the safer snprintf):

strcpy(b.label, "pump");

Size matters. label holds 12 bytes, so the longest text it can store is 11 characters plus the terminating zero. strcpy does not check this. A longer string overwrites the next members, silently corrupting node_id and temp_c. When the text comes from outside, limit it with snprintf(b.label, sizeof b.label, "%s", text).

Reading Input Into Members

Members are ordinary variables, so scanf can fill them. Numeric members need the address-of operator &, while a character-array member already decays to an address, so it does not:

scanf("%11s %d %f", c.label, &c.node_id, &c.temp_c);

The 11 in %11s is a field width that stops scanf from writing more than 11 characters plus the terminator into a 12-byte array. Always add it.

A Complete Program

Save the following as ep_struct_access.c. It combines every technique so far: brace initialization, strcpy, scanf, a whole-structure copy, and a comparison of members.

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

struct sensor_node {
    char  label[12];
    int   node_id;
    float temp_c;
};

int main(void)
{
    struct sensor_node a = { "boiler", 7, 81.5f };
    struct sensor_node b, c;

    strcpy(b.label, "pump");      /* arrays cannot be assigned with = */
    b.node_id = 8;
    b.temp_c  = 45.25f;

    printf("Enter label id temp for node c: ");
    if (scanf("%11s %d %f", c.label, &c.node_id, &c.temp_c) != 3) {
        fprintf(stderr, "bad input\n");
        return 1;
    }

    printf("a : %-8s %d %.2f\n", a.label, a.node_id, a.temp_c);
    printf("b : %-8s %d %.2f\n", b.label, b.node_id, b.temp_c);
    printf("c : %-8s %d %.2f\n", c.label, c.node_id, c.temp_c);

    struct sensor_node hot = a;   /* whole-struct copy */
    hot.node_id = 99;
    printf("a.node_id = %d, hot.node_id = %d\n", a.node_id, hot.node_id);

    if (a.temp_c > b.temp_c)
        printf("%s is hotter than %s\n", a.label, b.label);
    return 0;
}

Build and Run

$ gcc -std=c11 -Wall -Wextra -o ep_struct_access ep_struct_access.c
$ echo "tank 9 63.75" | ./ep_struct_access

The echo pipe feeds the input line so you can see a repeatable result. You can also run ./ep_struct_access and type the values yourself.

Expected Output

Enter label id temp for node c: a : boiler   7 81.50
b : pump     8 45.25
c : tank     9 63.75
a.node_id = 7, hot.node_id = 99
boiler is hotter than pump

The first line looks joined because the piped input does not echo a newline after the prompt; when you type interactively, your Enter key breaks the line. The fourth line is the key lesson: hot started as a copy of a, but changing hot.node_id left a.node_id at 7. The two variables are independent.

Copying and Comparing Whole Structures

Assignment between two structures of the same type copies every member in one statement, even the characters inside array members. This is one of the few places where C copies an array for you. Comparison is the opposite story: there is no == for structures. The compiler cannot decide whether you want to compare padding bytes, strings by content, or floats with tolerance. Compare member by member instead, using strcmp for text.

OperationAllowed?How
Assign one structure to anotherYeshot = a;
Compare two structuresNoCompare members one by one
Compare two membersYesa.temp_c > b.temp_c
Print a whole structure with one %NoPrint each member
Assign a string to a char array memberNot with =strcpy or snprintf

Common Compiler Errors and Their Meaning

Two mistakes appear constantly. Here is a tiny program that contains both:

struct sensor_node { int node_id; float temp_c; };

int main(void)
{
    struct sensor_node a = { 1, 2.0f };
    struct sensor_node b = { 1, 2.0f };
    sensor_node.temp_c = 5.0f;   /* tag used instead of a variable */
    if (a == b) return 1;        /* structures cannot be compared with == */
    return 0;
}
error: 'sensor_node' undeclared (first use in this function)
error: invalid operands to binary == (have 'struct sensor_node' and 'struct sensor_node')

The first error appears because sensor_node is only a tag, not a variable, so the dot has nothing on its left to work with. The second is the missing structure comparison. Both fixes are short: use a.temp_c = 5.0f; and compare the members you care about.

Real-World Use Cases

  • Sensor drivers: store the latest reading in dev.temp_c from an interrupt or polling routine and use it elsewhere in the program.
  • Configuration screens: read user input directly into cfg.baud and cfg.parity.
  • Snapshots: copy a live structure into a second variable, work on the stable copy, and never worry about it changing midway.

Best Practices

  • Check the return value of scanf before using the members it fills.
  • Bound every string copy to the size of the destination member.
  • Compare floating-point members using a tolerance, not exact equality.
  • Performance: a whole-structure copy of a large structure costs a block copy. In hot paths, pass a pointer to the structure (coming up in this chapter) instead of copying it.
  • Security: unbounded input into a fixed-size member is the classic buffer overflow. Field widths and snprintf are your first line of defense.

Summary and Key Takeaways

Remember

  • Use variable.member to reach a member; the left side must be a variable, never the tag.
  • A member behaves like any ordinary variable of its type.
  • Text members need strcpy or snprintf, not =.
  • Same-type structures can be assigned in one statement and stay independent afterwards.
  • Structures cannot be compared with ==; compare members.

Conclusion

You now have the complete basic toolkit for structures: define, declare, initialize and access. That is enough to model devices, configurations and records in your own embedded programs. The final lecture for these pages brings it all together with a small thermal-monitor lab, followed by a quiz and a set of interview questions to test what you learned.

Frequently Asked Questions

How do I access a structure member in C?

Use the dot operator between the structure variable and the member name, for example a.node_id.

Why can I not write student.name when student is the tag?

The tag is only a type name. The dot operator needs a variable that actually owns memory.

How do I assign a string to a structure member?

Use strcpy or, better, snprintf with the member’s size. Plain assignment does not work for character arrays.

Can I use scanf with structure members?

Yes. Pass &member for numbers and the member name itself for a character array, and add a field width for strings.

Can I compare two structures with ==?

No. C has no structure equality operator. Compare the members individually, and use strcmp for strings.

Does assigning one structure to another copy array members too?

Yes. Structure assignment copies every byte of every member, including arrays.

Is the dot operator used with pointers?

With a pointer to a structure you use the arrow operator instead. It is covered later in this chapter.

Where can I get a free embedded C course?

EmbeddedPathashala offers a free embedded C course with tested examples, quizzes and interview questions.

Almost Done With This Section

Finish with a hands-on thermal monitor lab, a quiz and interview questions on C structures.

💬 Need help or career guidance? Ask us!Contact Us →

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

×

🚀 BLE on Linux (BlueZ)

Hands-on course. Only ₹399

Enroll Now →