我无法理解为什么在该程序2-4中给出-1,它已经将int值分配给了指针而不是地址,我知道,但是当我编译它时,编译器给出了一些警告,但是编译了程序并执行了,但是...
程序
#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
答案 0 :(得分:6)
指针减法产生两个相同类型的指针之间的数组元素的数量
在Pointer subtraction confusion中了解有关此内容的更多信息。
但是,您的代码错误且格式错误,因为它调用了未定义行为。请在启用警告的情况下进行编译,您将获得:
main.c: In function ‘main’:
main.c:12:7: warning: assignment makes pointer from integer without a cast [-Wint-conversion]
p = arr[1];
^
main.c:13:7: warning: assignment makes pointer from integer without a cast [-Wint-conversion]
q = arr[3];
^
main.c:15:12: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘long int’ [-Wformat=]
printf("P-Q: %d, P: %d, Q: %d", (p - q), p, q);
^
main.c:15:12: warning: format ‘%d’ expects argument of type ‘int’, but argument 3 has type ‘int *’ [-Wformat=]
main.c:15:12: warning: format ‘%d’ expects argument of type ‘int’, but argument 4 has type ‘int *’ [-Wformat=]
但是仍然会发生错误。对于警告,我只使用了-Wall
标志。
为了使代码有意义,您可以仅将p
和q
声明为简单的int
而不是指针。
或者,您可以这样做:
p = &arr[1];
q = &arr[3];
printf("P-Q: %td, P: %p, Q: %p", (p - q), (void *)p, (void *)q);
得到这样的东西:
P-Q: -2, P: 0x7ffdd37594d4, Q: 0x7ffdd37594dc
请注意,我使用了%td
for printing the result of the subtraction of pointers。
答案 1 :(得分:6)
严格来说,发生的事情完全取决于您的编译器和平台...但是让我们假设我们使用的是典型的编译器,而忽略了警告。
让我们进一步简化您的问题:
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
:
p - q = (2 - 4) / sizeof(int)
= (-2) / 4
= -1
我建议尝试使用您自己的两个p
和q
值,看看会发生什么。
具有不同的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;
}