Jump to content

Question about operators

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
4 replies to this topic

#1
DarkLordoftheMonkeys

DarkLordoftheMonkeys

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 255 posts
What is the difference between the dot operator (.) and the arrow operator (->) in C?
Life's too short to be cool. Be a nerd.

#2
ZekeDragon

ZekeDragon

    Writes binary right handed and hex left handed

  • Moderators
  • 2,103 posts
The dot operator is the static access operator, it's for working with non-pointer structs and accessing the fields in those structs. The arrow operator is for accessing fields from structs that are referenced to by pointers. Consider the following code:
#include <stdlib.h>
#include <stdio.h>

typedef struct
{
    int a;
    int b;
} MyStruct;

int main(void)
{
    MyStruct str;
    MyStruct *p_str = malloc(sizeof(MyStruct));

    str.a = 10; str.b = 20;
    p_str->a = 15; p_str->b = 30;

    printf("MyStruct a: %d, b: %d\n", str.a, str.b);
    printf("MyStruct* a: %d, b: %d\n", p_str->a, p_str->b);
}

It should be noted that the arrow operator is exactly equivalent to this:
(*p_str).a = 15;
However the arrow is a bit cleaner looking.
Wow I changed my sig!

#3
thechef

thechef

    Learning Programmer

  • Members
  • PipPipPip
  • 79 posts
Is it true that the arrow is also more powerful than the dot operator? I think I remember a teacher of mine saying that it could access private members of classes.

#4
ZekeDragon

ZekeDragon

    Writes binary right handed and hex left handed

  • Moderators
  • 2,103 posts
No, only the object itself can access private members, no matter what. The arrow -> operator and (*dereferencing) plus the dot . operator are precisely identical.
if (p_str->a == (*p_str).a) // Always returns true 

Wow I changed my sig!

#5
WingedPanther

WingedPanther

    A spammer's worst nightmare

  • Moderators
  • 16,831 posts
No. -> and . are just based on different objects (pointer to vs object).
Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog