Dot (.) vs arrow (->) operator in C

Difference between the arrow operator -> and dot . operator in C

A lot of beginners get confused between -> and . when accessing struct members so I will show you a small example.

We have a struct containing an int and a char* pointer.

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

struct Person {
	char* name;
	int age;
};

below we create a statically allocated Person variable. To initialize it’s values we use the dot (.) operator.

void main() {
	Person person;
	person.age = 20;
	person.name = (char*)calloc(10, sizeof(char));
	strcpy(person.name, "armstrong");

	printf("Person's name: %s and age: %d\n", person.name, person.age);
}

Output is:

Person's name: armstrong and age: 20

Now if we create below a *pointer to a Person struct and name it otherPerson we must use the arrow operator to access it’s members.

	Person* otherPerson;
	otherPerson = (Person*)calloc(1, sizeof(Person));
	otherPerson->age = 30;
	otherPerson->name = (char*)calloc(9, sizeof(Person));
	strcpy(otherPerson->name, "vladimir");

	printf("Person's name: %s and age: %d\n", otherPerson->name, otherPerson->age);

Output is:

Person's name: vladimir and age: 30

But the arrow operator pointer->member is just a fancy way of saying (*pointer).member

/* other way of printing otherPerson info */
	printf("Person's name: %s and age: %d\n", (*otherPerson).name, (*otherPerson).age);

Output is:

Person's name: vladimir and age: 30

So either using pointer->member or (*pointer).member you get the same result. Though arrow operator has it’s use because you can clearly see which variables are pointers.

FacebookTwitterLinkedin