Reputation: 192
I found this code in the internet for adding two numbers using pointers. couldn't understand how it is working? Any help would be appreciated.
#include <stdio.h>
#include <conio.h>
int main()
{
int a,b,sum;
char *p;
printf("Enter 2 values : ");
scanf("%d%d",&a,&b);
p = (char *)a; // Using pointers
sum = (int)&p[b];
printf("sum = %d",sum);
getch();
return 0;
}
Upvotes: 1
Views: 1381
Reputation: 73587
The following line interprets the value in a
as an address:
p = (char *)a;
&p[b]
is the address of the b
th element of the array starting at p
. So, as each element of the array has a size of 1, it's a char pointer pointing at address p+b
. As p
contains a
, it's the address at p+a
.
Finally, the following line converts back the pointer to an int:
sum = (int)&p[b];
But needless to say: it's a weird construct.
Please note that there are limitations, according to the C++ standard:
5.2.10/5: A value of integral type (...) can be explicitly converted to a pointer.
5.2.10/4: A pointer can be explicitly converted to any integral type large enough to hold it.
So better verify that sizeof(int) >= sizeof(char*)
.
Finally, although this addition will work on most implementations, this is not a guaranteed behaviour on all CPU architectures, because the mapping function between integers and pointers is implementation-defined:
A pointer converted to an integer of sufficient size (if any such exists on the implementation) and back to the same pointer type will have its original value; mappings between pointers and integers are otherwise implementation-defined.
Upvotes: 5
Reputation: 34583
As commented, it is valid, but horrible code - just a party trick.
p = (char *)a;
p
takes the value of a
entered as a supposed address.
sum = (int)&p[b];
the address of the b
th element of a char
array is at p + b
.
Since p == a
(numerically), the correct sum is obtained.
To take a worked example, enter 46 and 11.
p = (char *)a; // p = 46
sum = (int)&p[b]; // the address of p[b] = 46 + 11 = 57
Note: nowhere is *p
or p[b]
written or read, and size does not matter - except for the char
array, where pointer arithmetic is in units of 1
.
Upvotes: 2
Reputation: 1461
First a
is converted to a pointer with the same value. It doesn't point to anything really, it's just the same value.
The expression p[b]
will add b
to p
and refer to the value at that position.
Then the address of the p[b]
element is taken and convert to an integer.
Upvotes: 2