簡體   English   中英

(2 - 4 = -1)當int值分配給C中的指針時?

[英](2 - 4 = -1) when int value assigned to pointer in C?

我無法理解為什么在這個程序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

重復的問題提到:

指針減法產生相同類型的兩個指針之間的數組元素的數量

Pointer減法混淆中閱讀更多相關信息。

但是,您的代碼錯誤且格式錯誤,因為它會調用未定義的行為 請編譯並啟用警告,您將獲得:

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標志。


為了使代碼有意義,你可以將pq聲明為簡單的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來打印指針減法的結果

嚴格來說,發生的事情完全取決於您的編譯器和平台......但我們假設我們使用的是典型的編譯器而忽略了警告。

讓我們進一步簡化您的問題:

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

我建議嘗試幾個你自己的pq值來看看會發生什么。


pq不同的例子:

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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM