I have this code which does the trick:
#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;
}
Can someone please explain what is happening in the code?
p = (char*)a;
sum = (int)&p[b]; // adding a & b
I think it is worth adding to the other answers a quick explanation of pointers, arrays and memory locations in c.
Firstly arrays in c are just a block of memory big enough to hold the number of items in the array (see http://www.cplusplus.com/doc/tutorial/arrays/)
so if we said
Assuming int is 32 bits we would have a block of memory 5*32bits = 160bits long.
As C is a low level language it tries to be as efficient as possible, therefor stores the least amount of information about arrays as possible, in this case the least amount possible is the memory address of the first element. So the type of example could be expressed as
Or example points to an int. To get the items in the array you then add the correct number to the address stored in example and read the number at that memory address.
If we assumed memory look like
So
could be expressed as
The sizeof(int) is 4 (int is 32 bits, or 4 * 8 bit bytes). If you where trying to do addition you would want a char which is 8 bits or 1 * 8 bit bytes.
So back to you code
So sum is assigned the address of the 21st element of the array.
Long winded explanation.