What is the difference between the dot operator (.) and the arrow operator (->) in C?
Question about operators
Started by DarkLordoftheMonkeys, Jan 28 2010 03:30 PM
4 replies to this topic
#1
Posted 28 January 2010 - 03:30 PM
Life's too short to be cool. Be a nerd.
|
|
|
#2
Posted 28 January 2010 - 03:48 PM
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:
It should be noted that the arrow operator is exactly equivalent to this:
#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
Posted 28 January 2010 - 06:43 PM
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
Posted 28 January 2010 - 07:56 PM
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
Posted 28 January 2010 - 07:59 PM
No. -> and . are just based on different objects (pointer to vs object).


Sign In
Create Account


Back to top









