Thread: typecasting a char pointer

1. typecasting a char pointer

Hello people,
How do u add 2 numbers without using the plus operator.
This is 1 of the many methods i came across.
I allllmost got it, but not quite.

This is the code i followed
-------------------------
Code:
```#include< stdio.h >
int main()
{
int a=30000,b=20,sum;
char *p;
p=(char *)a;
sum= (int)&p[b]; //adding a & b
printf("%d",sum);
return 0;
}```

This is my understanding until now
---------------------------------
1)The number 30000 is converted to a char pointer. So if u inspect p, it comes to 0x7530.
2)And b==20==0x14.
3)Now p[b] == *(p+b) , and &p[b] == &*(p+b) == p+b
4)Now p+b holds 0x7530 + 0x0014 = 0x7544
5)Then typecast 0x7544 into an int == 30020 == CORRECT SUM

My only doubt is , how can we convert an integer to a pointer like that. ( i mean , typecasting 30000 to 0x7530)
I mean, thats weird.
Is the answer that i just have to believe it.
Can some1 lend more light on this topic and probably even tell me a quick line about typecasting ?

2. No. All of that is terribly wrong.

p[ b ] is *(p + b) is p[ 20 ] is *(p + 20) is 20 bytes past p which is no where you should be trying to access.

Quzah.

3. Your little 'magic' trick only worked because a char is 1 byte. Hence a direct similarity to what you set out to do, e.g. add 20. What in reality you are doing is playing around with memory that isn't allocated and thus not yours to play with. Listen to quzah. There are a lot of 'tricks' you can do in programming languages using knowledge of how compilers work and playing odds. These all generally result in undefined behavior and should not be used for any real program.

4. What that code does will probably generate the right machine instructions to end up giving you the result you want. However it's really not nice.

However when you do that kind of thing, you're basically like the guy at the top of this ladder... http://www.funatiq.com/images/crazy-men-and-ladders.jpg

5. This is a dodgy little trick that exploits the fact that the size of a char is (usually) 1. As Quzah says, it's bad form to do anything involving memory you haven't allocated.

In this case it's pretty harmless though, because nowhere does this code change or look at information at those unallocated memory locations- just their addresses.

If you want a really cheesy way of avoiding the + operator:
Code:
`c = a - ( 0 - b );`

6. Originally Posted by TheBigH
char is (usually) 1
Always.

Quzah.

Popular pages Recent additions