I found the following code on internet for adding two numbers using pointers:-

``````#include<stdio.h>
int main()
{
int a=30000,b=20,sum;
char *p;

p=(char *)a;
sum= (int)&p[b];
printf("%d",sum);
return 0;

}``````

But I can't understand how p holds the value 30000 or how the result of the program is addition of 30000 and 20..

And another small question.. What does the following statement declare:

``char *a[][40];``

What does '40' signify in this? Please help me out!!

2
Contributors
1
Reply
3
Views
7 Years
Discussion Span
Last Post by Narue

>But I can't understand how p holds the value 30000 or how the result of the program is addition of 30000 and 20..
Presumably this hideous trick is meant to add two numbers without using the + operator. a is converted to a pointer to char, thus making the address pointed to by be 30000. Then the subscript operator is used to get to an object at an offset of b beyond the address pointed to by p. b is 20 and p+140==30020 (p is a pointer to char so that the step size is 1 rather than sizeof(int)). Use the address-of operator on the resulting object, convert the address back to int, and you've got the effect of a+b.

>What does the following statement declare: [ `char *a[][40];` ]
Break it down from the inside out:

``````a       // a is an
[]     // array of undefined size of
[40] // arrays of 40
*        // pointers to
char          // char``````

Edited by Narue: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.