簡體   English   中英

有人可以解釋這個程序的輸出嗎?

[英]Can someone explain output of this program?

這個程序的輸出是:

XBCDO 海爾

有人可以解釋為什么會這樣嗎?

#include<stdio.h>
void swap(char **p, char **q) {
    char *temp = *p;
    *p = *q;
    *q = temp;
}

int main() {
    int i = 10;
    char a[10] = "HELLO";
    char  b[10] = "XBCDE";
    swap(&a, &b);
    printf("%s %s", a, b);
}

您對指針和數組之間的區別感到困惑。 (這該語言的一個令人困惑的部分。) swap需要指向指針的指針,但您已經給了它指向數組的指針。 這是一個如此嚴重的錯誤,即使您沒有打開任何警告,GCC 也會發出警告(它應該發出硬錯誤,但是一些非常非常舊的代碼故意這樣做,他們不想破壞它)。

$ gcc test.c
test.c: In function ‘main’:
test.c:16:10: warning: passing argument 1 of ‘swap’ from incompatible pointer type [-Wincompatible-pointer-types]
     swap(&a, &b);
          ^
test.c:3:1: note: expected ‘char **’ but argument is of type ‘char (*)[10]’
 swap(char **p, char **q)
 ^~~~
test.c:16:14: warning: passing argument 2 of ‘swap’ from incompatible pointer type [-Wincompatible-pointer-types]
     swap(&a, &b);
              ^
test.c:3:1: note: expected ‘char **’ but argument is of type ‘char (*)[10]’
 swap(char **p, char **q)
 ^~~~

該錯誤導致程序具有未定義的行為——它根本不需要做任何有意義的事情。

您可能嘗試編寫的程序如下所示:

#include <stdio.h>

static void swap(char **p, char **q)
{
    char *temp = *p;
    *p = *q;
    *q = temp;
}

int main(void)
{
    char a[10] = "HELLO";
    char b[10] = "XBCDE";
    char *c = a;
    char *d = b;
    swap(&c, &d);
    printf("%s %s", c, d);
}

該程序的輸出是XBCDE HELLO ,我認為這正是您所期望的。 cd實際上是指針,它們被設置為指向數組ab的第一個元素; 當應用於cd時, swap按預期工作。

如果cdab不同沒有任何意義,那么您需要掌握一本好的 C 教科書,並且需要閱讀有關指針的章節並完成所有練習。 (如果它沒有至少一整章關於指針的內容,加上練習,它就不是一本好的 C 教科書。)

暫無
暫無

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

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