CooperJames
CooperJames

Reputation: 79

Pointer to array structure

I have a small program which when compiling throws me the following errors

error #2168: Operands of '+' have incompatible types 'struct agenda' and 'int'.

error #2113: Left operand of '.' has incompatible type 'int'.

error #2088: Lvalue required.

This is the code that I have done

#include <stdio.h>

struct agenda{
    int order, cellular;
    char name[30], last_name[30], street[30], city[30], mail[50];
}contact[10];

int main(void)
{
    struct agenda *ptrcontact;
    ptrcontact = &contact[0];

    (*ptrcontact+3).order = 3;

    printf("\n\n %d", (*ptrcontact).order);
    return 0;
}

because it throws these errors and how to fix them?

Upvotes: 0

Views: 377

Answers (4)

Akilesh Reddzz
Akilesh Reddzz

Reputation: 36

the error is in the lines (*ptrcontact+3).order = 3; and printf("\n\n %d", (*ptrcontact).order);. In this instructions use -> instead of . the errors will be solved.

Upvotes: 0

Roman Nikitchenko
Roman Nikitchenko

Reputation: 13036

Your problem here is operations priority:

 (*ptrcontact+3).order = 3;

This derefers ptrcontract and then tries to add number to dereferred structure. Which gives you exact situation you report.

My recommendations:

Either avoid address ariphmetics in such cases. Operate array indexes.

int baseIndex = 0;
contact[baseIndex + 3].order = 3;

Or if you really have to do so, hide address arithmetic from outside:

(pcontact + 3)->order = 3;

And finally learn C language operations priority or, to do it once (but some C people don't like C++), C++ operations priority

Upvotes: 0

Sourav Ghosh
Sourav Ghosh

Reputation: 134316

You need to change

(*ptrcontact+3).order = 3;

to

ptrcontact[3].order = 3;

or, at least,

(*(ptrcontact+3)).order = 3;

or,

(ptrcontact + 3)->order = 3;

Otherwise, as per the precedence rule, * has higher precedence over +, causing the error.

Just to add to that, ptrcontact is a pointer ( to struct agenda) and can be used as an operand to + operator.

OTOH, *ptrcontact is of type struct agenda and cannot be used as an operand to + operator.

Upvotes: 6

Lev Kuznetsov
Lev Kuznetsov

Reputation: 3728

You are dereferencing the pointer which yields the struct and obviously you can't add anything to that. Dereference operator has the highest priority, you need to do it like this: (*(ptr + 3)).order or use the arrow instead of star dot: (ptr + 3) -> order

Upvotes: 2

Related Questions