簡體   English   中英

以下程序的輸出是什么? 您如何跟蹤這樣的程序?

[英]What is the output of the following program? How do you trace such a program?

我必須確定以下程序的輸出。 答案是BEADC ,但是我不確定如何跟蹤程序。 這是我所知道的:

我們首先聲明一個數據類型為trip名為road_trip的結構。 在主程序中,我們為成員place分配值。 然后創建一個鏈表,其中起始節點為s2 ,結束節點為s3 因為您可以看到起始節點的地址存儲在單獨的指針ptr ,所以通常將其稱為頭指針。 s3是鏈表的結尾,因為如果看到s3您可能會注意到s3 nextNULL 這意味着s3沒有引用任何其他節點。

我不明白的是程序如何按順序打印存儲在s2B ), s5E ), s1A ), s4D )和s3C )中的值。 我確定這與我在之后寫評論的兩行有關。 一個解釋會很有幫助。

#include <stdio.h>

typedef struct road_trip
{
    char place;
    struct road_trip* next;
}trip;

int main (void)
{
    trip s1, s2, s3, s4, s5, s6;
    trip *ptr;

    s1.place = 'A';
    s2.place = 'B';
    s3.place = 'C';
    s4.place = 'D';
    s5.place = 'E';

    s5.next = &s1;
    ptr = &s2;
    s1.next = &s4;
    s3.next = NULL;
    s4.next = &s3;
    s2.next = &s5;

    while (ptr != NULL)
    {
        printf("%c ", ptr -> place);    /*I don't get this line*/
        ptr = ptr -> next;    /*I don't get this line*/
    }
    return 0;
}
 printf("%c ", ptr -> place); /*I don't get this line*/ ptr = ptr -> next; /*I don't get this line*/ 
  • 在這里, ptr是指向trip的指針(即 struct road_trip
  • 當您想使用指針訪問結構的成員時,則使用-> (“ 結構解除引用運算符”)運算符

答案是“ BEADC”,但我不確定如何跟蹤程序。

s5.next = &s1;
ptr = &s2;
s1.next = &s4;
s3.next = NULL;
s4.next = &s3;
s2.next = &s5;

上面的代碼對跟蹤程序很有用...

這里

  • ptr指向s2

和:

  • s2 next成員指向s5
  • s5 next成員指向s1
  • s1 next成員指向s4
  • s4 next成員指向s3
  • s3 next成員指向NULL

您在問題中給出了正確的解釋


我不明白的是程序如何按順序打印存儲在s2 (B), s5 (E), s1 (A), s4 (D)和s3 (C)中的值

現在,當您以這種方式使用ptr進行迭代時:

while (ptr != NULL)
{
    printf("%c ", ptr -> place);
    ptr = ptr -> next;
}

跟蹤循環:

  • 第一次迭代 B被打印,因為ptr指向s2 ,因此ptr->places2.place相同(因此使用Structure取消引用運算符訪問了place成員的值)
  • 然后ptr = ptr->next是相同ptr = s2->next並且因此ptr = &s5作為s2->next點至s5

  • 同樣,此循環繼續進行,您將以連接其next成員的方式獲得輸出

  • 循環在打印s3之后結束,因為s3->next指向NULL ,因此在打印s3之后ptr變為=NULL


進一步閱讀:

  • 這是鏈表的典型實現(單擊以了解更多信息)

  • 結構的一個成員指向列表的下一個結構的這種類型的列表稱為單鏈接列表 (單擊以了解更多信息)

ptr是指向s2的指針,因此顯示char ptr-> place將顯示行程s2的位置。 然后將ptr更改為下一個指針-s2的下一個是s5。 顯示ptr-> place將顯示行程s5的現在位置。 然后,ptr更改為s5的下一個,即s1,直到到達s3(下一個指針為NULL)為止。

暫無
暫無

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

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