Jean
Jean

Reputation: 22695

GCC Error: Invalid operands to binary +

Why is GCC giving me this error ? What am I doing wrong here ?

 temp.c: In function main:
 temp.c:6: error: invalid operands to binary +

Code:

 main()
 {
     char *Address1,*Address2,*NewAddress;
     Address1= (char*)0x12;
     Address2= (char*)0x34;
     NewAddress = Address1+Address2;
 }

Upvotes: 2

Views: 10258

Answers (6)

DonMilne
DonMilne

Reputation: 1

These answers are awful. I accept that recent C standards may deprecate the feature, but there are valid reasons to add and subtract pointers, e.g. when one is relative or you want to create a relative address. C was always intended to be a high level assembler and relative addressing is a fundamental OP in all modern CPUs.

As to the proposed solutions: what is VERY bad practice is to cast each pointer to integer and then subtract, since a pointer may not fit into an integer. However (INT)(p2-p1) ought to be safe, assuming the P1 and P2 addresses are within the same context, i.e. known to be in the same buffer.

Upvotes: -4

user405725
user405725

Reputation:

C does not permit adding two pointers. The best explanation I found for this, not touching any standard, is Rouben Rostamian's quote:

If you and I live on the same street, the difference of our house numbers is some sort of indication of the distance between our houses.

Now, you tell me, what meaning is there in the sum of our house numbers?

So the whole operation does not make any sense. It is pretty logical, isn't it? You can do this, however:

NewAddress = (char *)(0x12 + 0x34);

Upvotes: 5

designerrr
designerrr

Reputation: 322

Because those variables are pointers, try convert to int.

NewAddress = (char *)((int)Address1 + (int)Address2);

Upvotes: 0

Dan Fego
Dan Fego

Reputation: 14004

In C, you can't add two pointers. If you think about it, it doesn't logically make any sense to try. To fix this, you can cast one of the pointers to an integral value before adding:

NewAddress = (long)Address1 + Address2;

Upvotes: 0

Why do you want to do that?

The C language forbids addition of two pointers. It only defines (with severe restrictions) the addition of a pointer and an integer.

Basically, you can only add to a pointer an integer small enough so that the result was inside, or at the ending border, of some allocated memory zone.

Upvotes: 6

Pubby
Pubby

Reputation: 53047

You can't add pointers together, that would be nonsensical.

What is allowed is adding integral values to pointers:

char *Address1,*NewAddress;
unsigned Offest;
     Address1= (char*)0x12;
     Offset= 0x34;
     NewAddress = Address1+Offset

Upvotes: 0

Related Questions