Hi guys,

Is there a difference between these two:

struct->variable
struct.variable

?

Dani AI

Generated

As and correctly noted, -> is the member operator used with pointers to a struct (or union) and . is used with an actual struct object. Below are a few concise, practical clarifications and common gotchas that often help when that basic rule still leaves questions.

The important equivalence to remember is that p->m is the same as (*p).m. Operator precedence can bite when casts are involved — the expression is parsed before a cast unless parentheses force the intended grouping. For example:

/* parsed as: (struct Foo*)(ptr->member)   — usually NOT what's wanted */
(struct Foo*)ptr->member

/* cast the pointer first, then access the member */
((struct Foo*)ptr)->member

Pointers-to-pointers and arrays are common places for confusion. Given struct Node *head;, a pointer-to-pointer is handled like this:

struct Node **pp = &head;
(*pp)->value = 5;   /* must dereference pp first, then use -> */

And array/offset equivalence is handy to remember:

people[i].age == (people + i)->age

Semantics and safety notes: using . on a struct value copies nothing by itself, but passing a struct by value to a function copies the whole struct; passing a pointer avoids that copy and lets the callee modify the original. Always check for NULL before dereferencing pointers, enable compiler warnings (e.g. -Wall -Wextra), and prefer the form that makes ownership and lifetime clear — use . for owned/stack objects and -> when working with pointers (heap or shared).

Recommended Answers

All 3 Replies

Yes, the first is a pointer while the other is not. Example

struct something
{
  int variable;
  // blabla
};

struct somtehing* ptr; // ptr->variable
struct something obj; // obj.variable

Yes, the first is a pointer while the other is not. Example

struct something
{
  int variable;
  // blabla
};

struct somtehing* ptr; // ptr->variable
struct something obj; // obj.variable

Thank You very much for the fast answer!

Member Avatar for Member #866461

a->variable = the variable field of the struct a points to

a.variable = the variable field of the struct a

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.