*ฅ^•ﻌ•^ฅ* ✨✨  HWisnu's blog  ✨✨ о ฅ^•ﻌ•^ฅ

C: dot vs arrow notation

Introduction

In this short article we are going to learn the difference between what and when to use dot notation and arrow notation.

Dot notation

Used when we have a variable that is a struct itself, not a pointer to a struct. In the given code, sample is a variable of type S, which is a struct. To access the members of sample, we use dot notation, like this: sample.x

Consider the C struct below:

typedef struct S {
    int x;
} S;

int main()
{
    S sample = {.x = 2};
    sample.x += 1;
};

sample now has the value of 3 (2+1).

Arrow notation

Used when we have a pointer to a struct. In the given code, vample is a pointer to a struct of type S. To access the members of the struct that vample points to, we use arrow notation, like this: vample->x

typedef struct S {
    int x;
} S;

int main()
{
    S sample = {.x = 5};
    S *vample = &sample;
    vample->x += 2; // the same as: (*vample).x += 2;
};

vample now has the value of 7 (5+2).

When we have a pointer to a struct, we need to dereference the pointer to get the memory location of the struct before we can access its members. The arrow notation (->) is a shorthand way of doing this dereferencing.

In other words, vample->x is equivalent to (*vample).x. The * operator dereferences the pointer vample, and then the dot notation is used to access the x member.

#c #low level #programming