# Using the -> operator in C language

Status
Not open for further replies.

#### shaiko

Hello,

What does the C -> operator do?
How does it work?

#### doraemon

##### Super Moderator
Staff member
Hello!

The -> can be used for a pointer, the . can be used for an actual object.

Example:

Code C - [expand]1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
typedef struct {
int a;
int b;
} AStruct;

//    Case 1: an actual instance

AStruct MyAStruct;

//   If you want to access member a or b, you use .
MyAStruct.a = 1;
MyAStruct.b = 2;

//    Case 2: a pointer

AStruct * MyAStrucyPointer;

MyAStructPointer = &MyAStruct;

//    In this case, if you want to access the members through the pointer:

MyAStructPointer->a = 1;
MyAStructPointer->b = 2;

Well, I don't see anything else to add.
It's like the phone. If you talk to somebody close to you, you talk directly, otherwise, you talk through the phone.

Dora.

shaiko

### shaiko

Points: 2

#### shaiko

Thanks a lot.
Is there a different syntax that can do the same thing - without using the -> operator ?

#### doraemon

##### Super Moderator
Staff member
Hello!

If you want to do it without the -> operator, just take the actual instantiation of your structure / object.
Anyway in the embedded world, you usually don't use memory allocation, therefore you can always
find an actual instanciation of some kind. For example, if you use MyAStruct somewhere, you can
declare anywhere in your program as extern AStruct MyAStruct, in which case you don't need a pointer
to access it.
By the way, why are you afraid of -> ?

Dora.

shaiko

### shaiko

Points: 2

#### FvM

##### Super Moderator
Staff member
If we presume that your code is using a pointer to a structure for a good reason (e.g. because multiple objects of the same type are accessed) there's no reasonable alternative. If the pointer is accessing a simple array of structure, using the array index can be an alternative, as in the below example. x and y are assigned with the same data. Which variant is more efficient strongly depends on the processor architecture and compiler intelligency.

Code C - [expand]1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
typedef struct
{
int a;
char b;
} STRUCT1, *PSTRUCT1;

STRUCT1 s[10];
PSTRUCT1 ps;
int i;
int x;
int y;
for (i=0, ps = s;i<10;i++,ps++)
{
x = ps->a;
y = s[i].a;
}

shaiko

### shaiko

Points: 2

#### shaiko

By the way, why are you afraid of -> ?
Not afraid - I want to be familiar with more ways to do the same thing so I recognize when I see them...

If you want to do it without the -> operator, just take the actual instantiation of your structure / object.

#### doraemon

##### Super Moderator
Staff member
Hello!

The example is already posted. See case 1.

Dora.

shaiko

Points: 2