0

Is it possible add two pointers? C language

int *ptr1; int *ptr2; ptr1 = ptr1 + ptr2; // ?

4th Dec 2016, 5:35 AM
Ramesh Marisa
8 Answers
+ 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.
4th Dec 2016, 12:14 PM
Ramesh Marisa
+ 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.
4th Dec 2016, 12:22 PM
Kirk Schafer
Kirk Schafer - avatar
+ 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
4th Dec 2016, 9:59 AM
Kirk Schafer
Kirk Schafer - avatar
+ 1
int sum = (int)ptr1 + (int)ptr2; int dif = ptr1 - ptr2;
4th Dec 2016, 12:17 PM
Kirk Schafer
Kirk Schafer - avatar
0
you are adding the addresses they point to. unless you are adding them as offsets to an other address then it's meaningless
4th Dec 2016, 6:01 AM
Elio
Elio - avatar
0
after typecasting ptr1 & ptr2 are not pointers
4th Dec 2016, 12:19 PM
Ramesh Marisa
0
try without typecasting
4th Dec 2016, 12:19 PM
Ramesh Marisa
0
Is that possible to store a value at reslut of addition of two adress
31st Oct 2020, 6:05 PM
prasad Voleti
prasad Voleti - avatar