(2-4 = -1)当int值分配给C中的指针吗? [英] (2 - 4 = -1) when int value assigned to pointer in C?
问题描述
我无法理解为什么在此程序2-4中给出-1,它已经将int值分配给了指针而不是地址,我知道,但是当我编译它时,编译器给出了一些警告,但是编译了程序并执行了,但是...
I am unable to get that why in this program 2 - 4 gives -1, it has assigned int values to pointers rather than addresses, I know but while I compiled it compiler gave some warnings but compiled the program and it executed but...
程序
#include<stdio.h>
int main(void) {
int *p, *q;
int arr[] = {1,2,3,4};
// I know p and q are pointers and address should be assigned to them
// but look at output, why it evaluates (p-q) to -1 while p as 2 and q as 4
p = arr[1];
q = arr[3];
printf("P-Q: %d, P: %d, Q: %d", (p - q), p, q);
return 0;
}
它给出了
P-Q: -1, P: 2, Q: 4
推荐答案
严格来说,发生的事情完全取决于您的编译器和平台...但是让我们假设我们使用的是典型的编译器,而忽略了警告.
Strictly speaking, what happens depends entirely on your compiler and platform... but let's assume we're using a typical compiler and ignoring the warnings.
让我们进一步简化您的问题:
Let's simplify your question further:
p = 2;
q = 4;
printf("P-Q: %d, P: %d, Q: %d", (p - q), p, q);
产生相同的古怪结果:
P-Q: -1, P: 2, Q: 4
正如@gsamaras指出的那样,我们正在尝试减去两个指针.让我们尝试看看这怎么会导致-1
:
As @gsamaras pointed out, we're trying to subtract two pointers. Let's try and see how this might result in -1
:
p - q = (2 - 4) / sizeof(int)
= (-2) / 4
= -1
我建议尝试几个您自己的p
和q
值以查看会发生什么.
I suggest trying a couple of your own p
and q
values to see what happens.
p
和q
不同的示例:
p - q = ??
==========
0 - 0 = 0
0 - 1 = -1
0 - 2 = -1
0 - 3 = -1
0 - 4 = -1
1 - 0 = 0
1 - 1 = 0
1 - 2 = -1
1 - 3 = -1
1 - 4 = -1
2 - 0 = 0
2 - 1 = 0
2 - 2 = 0
2 - 3 = -1
2 - 4 = -1
3 - 0 = 0
3 - 1 = 0
3 - 2 = 0
3 - 3 = 0
3 - 4 = -1
4 - 0 = 1
4 - 1 = 0
4 - 2 = 0
4 - 3 = 0
4 - 4 = 0
在以下位置使用gcc -fpermissive
生成:
#include <stdio.h>
int main() {
printf("p - q = ??\n");
printf("==========\n");
for (int i = 0; i < 5; ++i) {
for (int j = 0; j < 5; ++j) {
int* p = i;
int* q = j;
printf("%d - %d = %2d\n", p, q, (p - q));
}
}
return 0;
}
这篇关于(2-4 = -1)当int值分配给C中的指针吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!