指针减去数组和变量中的指针

pointer minus pointer in array and variable

谁能帮我解决这个问题。 我认为指针是一个保存变量地址的对象。因此,当我减去指向指针的指针时。它得到了这个结果。

int a = 2;
int b = 7;
int* c = &a;
int* d = &b;
int e = c - d; // = 3


int array[] = { 1, 2, 6, 4, 7, 8, 5, 3 };
int* f = &array[0];
int* g = &array[8];
int h = g - f; // = 8 

你是对的,一个指针保存了一个对象在内存中的地址。在 C 和 C++ 中,我们可以进行指针运算,这让我们可以将指针彼此相减,甚至更多。减去指针可以得到内存中两个地址之间的距离。距离的单位由指针类型决定。这意味着减去两个 int* 将得出您的地址相差多少 int。在您的情况下,变量 e 将是 a 存储在内存中的位置与 b 存储在内存中的位置之间的距离。 运行 你的代码我得到了 e=1。我希望如此,因为 ab 是紧接着彼此定义的,因此预计它们将占据堆栈上的两个相邻空间,但我猜这是编译器决定的。 对于数组 另一方面,根据定义,所有元素都一个接一个地存储,因此任何数组的第一个和第八个元素之间的距离总是 8。另请查看以下代码:

int a = 2;
int b = 7;
int* c = &a;
int* d = &b;
int e = d - c; // e=1
//the unit of measurement for pointer subtraction is the type of the pointer
//therefore although first byte of b is stored 4 bytes (sizeof(int)) after the
//first byte of a, we get '1' as the distance. but we cast the pointer to another type
//say char, we get distance based on that type
int f= (char*)d-(char*)c;//f=4 or e*4 since sizeof(int)=4*sizeof(char) (on this particular environment)

在你的第一个例子中,减去独立指针是没有意义的。考虑你的例子:

int a = 2;
int b = 7;
int* c = &a;
int* d = &b;
int e = c - d; // Nonsense

如果你想做的是使用指针的操作“2 - 7”,那么你首先必须取消引用你的指针(评估你的指针指向的变量所持有的值):

int e = (*c) - (*d);