0
Is it possible add two pointers? C language
int *ptr1; int *ptr2; ptr1 = ptr1 + ptr2; // ?
8 Réponses
+ 2
Adding two pointers is illegal in c program
but pointer and integer addition is legal.
subtraction of two pointers is also legal.
multiplication & division of two pointers are also illegal.
+ 2
int sum = (int)ptr1 + (int)ptr2;
int dif = ptr1 - ptr2;
+ 2
Agreed; not sure if you can cast the second only and...I saw an explanation that described a use for this but I'm fine leaving my oversight for others to learn from. I'll upvote your result.
+ 1
Sure, they're just integers but you're likely to encounter a segfault if you use the result for at least a couple reasons:
These pointers aren't initialized and likely contain "random" values; the sum could even overflow.
Once initialized to values that make sense to your program, as written you may still try to access memory outside the legal address spaces of your program.
With control, potential uses include:
Iterating a string in columns, like every 12th character
With full system privileges, accessing memory in segment:offset form (as @Elio suggests)
Here's a nice comment on pointer dereferencing, contrasting Java and C++:
http://stackoverflow.com/a/2629758/3981745
0
you are adding the addresses they point to. unless you are adding them as offsets to an other address then it's meaningless
0
after typecasting ptr1 & ptr2 are not pointers
0
try without typecasting
0
Is that possible to store a value at reslut of addition of two adress