sum (adding 2 numbers ) without plus operator

后端 未结 9 662
借酒劲吻你
借酒劲吻你 2021-02-05 20:42

Can anyone explain the logic how to add a and b?

#include 

int main()
{
     int a=30000, b=20, sum;
     char *p;
             


        
9条回答
  •  余生分开走
    2021-02-05 21:10

    char *p;  
    

    p is a pointer (to element with size 1 byte)


    p=(char *)a;  
    

    now p points to memory with address a


    sum= (int)&p[b]; 
    

    p pointer can be use as array p[] (start address (in memory) of this array is a)

    p[b] means to get b-th element - this element address is a+b

    [ (start address)a + b (b-th element * size of element (1 byte)) ]

    &p[b] means to get address of element at p[b] but its address is a+b


    if you use pointer to int (mostly 4 bytes)

    int* p
    p = (int*)a;
    

    your sum will be a+(4*b)

提交回复
热议问题