Use Pointers to do addition operations without a plus sign
- 2020-06-15 09:49:29
- OfStack
We usually add with something like this
#include<stdio.h>
int main()
{
int a=2,b=3;
printf("%d\n",a+b);
return 0;
}
The result is 5, adding a and b
But how can we add without the plus sign? So let's look at one of the array operations
#include<stdio.h>
int main()
{
int a[]={1,2};
printf("%d\n",a[0]+a[1]);
return 0;
}
The result is 3, which is the same as the following code
#include<stdio.h>
int main()
{
int a[]={1,2};
printf("%d\n",*(a+0)+*(a+1));
return 0;
}
Because a [i] = * (a + i)
So let's just do 1 pointer
#include<stdio.h>
int main()
{
int a=2,b=3;
int *p=a,*q=b;
printf("%d\n",*p+*q);
return 0;
}
p and q point to the addresses of a and b respectively, calculate the sum of a and b, and the result is 5
Now use the pointer and just said a[i]=*(a+i) and variable location 1 combination
#include<stdio.h>
int main()
{
int a=2,b=3;
int *p;
printf("%d\t%d\n",&a,&b);
p=&a;
printf("%d\n",(int)&((char *)a)[b]);
return 0;
}
The output is
[
1638212 1638208
5
In front of the two values are respectively a and b address, because is int type and in the 32-bit compiler I use is stored in 4 bytes, however char type is according to 1 byte stored in one byte, use Pointers p variable a, see (char *) a first, it is a casting, converting a this variable char * type of address, ((char*)a)[b] moves the address back by b bytes, but ((char*)a)[b] is equal to *(a+b), we know & The alpha and alpha cancel each other out, so we have alpha & ((char*)a)[b], but it is still of type char*, and the preceding (int) casts its bit int for output.
When a and b, as defined by long at the time, were cast to int, long was 8 bytes and int was 4 bytes, then data would be lost.
Finally, as I just learned, you can test whether the compiler is 64-bit or 32-bit with Pointers. The 64-bit compiler pointer variable is 8 bytes, and the 32-bit compiler pointer variable is 4 bytes.
conclusion