繁体   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