Can anyone explain the logic how to add a
and b
?
#include
int main()
{
int a=30000, b=20, sum;
char *p;
The +
is hidden here:
&p[b]
this expression is equivalent to
(p + b)
So we actually have:
(int) &p[b] == (int) ((char *) a)[b]) == (int) ((char *) a + b) == a + b
Note that this technically invokes undefined behavior as (char *) a
has to point to an object and pointer arithmetic outside an object or one past the object invokes undefined behavior.
An alternative to the pointer arithmetic is to use bitops:
#include <stdio.h>
#include <string.h>
unsigned addtwo(unsigned one, unsigned two);
unsigned addtwo(unsigned one, unsigned two)
{
unsigned carry;
for( ;two; two = carry << 1) {
carry = one & two;
one ^= two;
}
return one;
}
int main(int argc, char **argv)
{
unsigned one, two, result;
if ( sscanf(argv[1], "%u", &one ) < 1) return 0;
if ( sscanf(argv[2], "%u", &two ) < 1) return 0;
result = addtwo(one, two);
fprintf(stdout, "One:=%u Two=%u Result=%u\n", one, two, result );
return 0;
}
p[b]
is the b-th element of the array p
. It's like writing *(p + b)
.
Now, when adding &
it'll be like writing: p + b * sizeof(char)
which is p + b
.
Now, you'll have (int)((char *) a + b)
which is.. a + b
.
But.. when you still have +
in your keyboard, use it.
As @gerijeshchauhan clarified in the comments, *
and &
are inverse operations, they cancel each other. So &*(p + b)
is p + b
.