为什么只允许地址减法而不允许除法/加法/乘法

为什么允许减法? 可以减去两个地址,因为两个地址之间的内存将是有效内存。 让我们假设内存Ptr_1和Ptr_2的地址是有效的。很明显,这两个地址之间的内存是有效的。 指针ptr_1指向0x1cb0010内存位置,ptr_2指向0x1cb0030内存位置。如果我们从ptr_2中减去ptr_1,那么内存区域将位于这两个位置之间,这显然是一个有效的内存位置。

null

C++

// C++ program to demonstrate that pointer
// subtraction is allowed.
#include <iostream>
using namespace std;
int main()
{
int * ptr_1 = ( int *) malloc ( sizeof ( int ));
int * ptr_2 = ( int *) malloc ( sizeof ( int ));
cout << "ptr_1:" << ptr_1 << " ptr_2: " << ptr_2 << endl;
cout << "Difference: " << ptr_2 - ptr_1;
free (ptr_1);
free (ptr_2);
return 0;
}
// This code is contributed by shivanisinghss2110.


C

// C program to demonstrate that pointer
// subtraction is allowed.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int * ptr_1 = ( int *) malloc ( sizeof ( int ));
int * ptr_2 = ( int *) malloc ( sizeof ( int ));
printf ( "ptr_1: %p  ptr_2: %p" , ptr_1, ptr_2);
printf ( "Difference: %lu" , ptr_2 - ptr_1);
free (ptr_1);
free (ptr_2);
return 0;
}


Output:ptr_1: 0x1cb0010 ptr_2: 0x1cb0030Difference: 8

为什么不允许加、乘、除或模?? 如果我们对ptr_1和ptr_2执行加法、乘法、除法或模运算,那么结果地址可能是有效地址,也可能不是有效地址。可能超出范围或地址无效。这就是编译器不允许对有效地址执行这些操作的原因。

C++

// C++ program to demonstrate addition / division
// / multiplication not allowed on pointers.
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int main()
{
int * ptr_1 = ( int *) malloc ( sizeof ( int ));
int * ptr_2 = ( int *) malloc ( sizeof ( int ));
cout << "addition:%lu multipicaion:%lu division:%lu" <<
ptr_2 + ptr_1<< ptr_2 * ptr_1<< ptr_2 / ptr_1;
free (ptr_1);
free (ptr_2);
return 0;
}
// This code is contributed by shivanisinghss2110


C

// C program to demonstrate addition / division
// / multiplication not allowed on pointers.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int * ptr_1 = ( int *) malloc ( sizeof ( int ));
int * ptr_2 = ( int *) malloc ( sizeof ( int ));
printf ( "addition:%lu multipicaion:%lu division:%lu" ,
ptr_2 + ptr_1, ptr_2 * ptr_1, ptr_2 / ptr_1);
free (ptr_1);
free (ptr_2);
return 0;
}


Output: prog.c: In function 'main':prog.c:8:60: error: invalid operands to binary + (have 'int *' and 'int *')printf("addition:%lu multipicaion:%lu division:%lu", ptr_2+ptr_1, ptr_2*ptr_1,ptr_2/ptr_1);
© 版权声明
THE END
喜欢就支持一下吧
点赞7 分享