簡體   English   中英

將指針的值傳遞給不修改指針的函數后,為什么會更改它?

[英]Why does the value of a pointer change after passing it to a function that does not modify the pointer?

main()的指針ptrTop初始化為指向int topDeck = 1 每次我運行程序時,(我認為)已取消引用的指針的值都會更改為不同的數字。 我認為問題在於deal()函數。 如果我在main()注釋掉對deal()的調用,則指針的值不會被修改。 我沒有編寫任何更改指針值的語句。 我圍繞可能與該問題相關的代碼部分編寫了注釋。

/* 
 * This is a card dealing program. 
 * the fucntion deal() keeps changing the value of 
 * the int pointer ptrTop declared in main(). sometimes, 
 * the value is what it is sopposed to be (1), but when i run 
 * the program again, it is a different value. I used 
 * gcc (GCC) 4.9.2 20150212 (Red Hat 4.9.2-6)
 */

int main(void) {

    int topDeck = 1;
    int *ptrTop = &topDeck;

    //this ptrTop is sopposed to keep track of the last
    //card dealt, but it randomly changes every time I run 

    unsigned int handSuit[5] = {0};
    unsigned int handFace[5] = {0};



    unsigned int deck[SUITS][FACES] = {0};


    deal(deck, face, suit, ptrTop, handSuit, handFace);

    printf("%i\n", *ptrTop);
    // If print the value while I comment out the deal() in line 55, 
    // the value of * ptrTop does not change.
    // this gives me reason to believe that deal() is causing the trouble.

}


void deal(unsigned int wDeck[][FACES], const char *wFace[], const char *wSuit[], 
    int *ptrTop, unsigned int handSuit[], unsigned int handFace[]) 
{
    size_t card;
    size_t row;
    size_t column;
    int top = *ptrTop;
    // i have to use top because if i don't the dea() function will print
    // more than 5 cards (it is sopposed to print a 5 card hand.

    // these for loops loop through the double scripted array wDeck
    for (card = top; card <= top + 4; ++card) {

        for (row = 0; row < SUITS; ++row) {

            for(column = 0; column < FACES; ++column) {

                if(wDeck[row][column] == card) {
                    printf( "%s of %s \n", wFace[ column ], wSuit[ row ]);
                    handFace[card] = column;
                    handSuit[card] = row;
                }
            }
        }
    }
    // *ptrTop = card;
    // the value of *ptrTop consistently becomes six if line above is uncommented.
    // I would think that the value should still be 1 
    // when the program is run in this state.
}

原因是:

 for (card = top; card <= top + 4; ++card)

當您有變量時,卡的索引從1到5

unsigned int handSuit[5] = {0};
unsigned int handFace[5] = {0};

這僅支持索引0到4。您可以越界訪問這些數組,並且作為未定義行為的副作用,您將覆蓋其他變量。

我不太確定您期望*ptrTop其他值是多少(六以外); 讓我們來看看deal

for (card = top; card <= top + 4; ++card)

記住,這是main初始化的top的值:

int topDeck = 1;
int *ptrTop = &topDeck;

因此,在deal ,您循環循環五次,對card遞增,然后在最后一次迭代中, for循環將第五次對card進行遞增,看得出它是6 ,並且由於6 <= 5為false,它將退出,如果你做*ptrTop = card; *ptrTop確實始終等於6。

暫無
暫無

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

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