为什么指针的值在传递给不修改指针的函数后会改变?

时间:2015-05-22 06:21:04

标签: c pointers

main() ptrTop中的指针初始化为指向int topDeck = 1。每次运行程序时,(我认为)取消引用指针的值都会变为不同的数字。我认为问题在于deal()功能。如果我在deal()中注释掉对main()的调用,则不会修改指针的值。我没有写任何改变指针值的语句。我围绕代码中可能与问题相关的部分撰写了评论。

/* 
 * 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.
}

2 个答案:

答案 0 :(得分:3)

这个模糊的循环是原因:

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

卡片的索引从1到5,而你有变量

Option Explicit
Sub CopyMacro()
    '// Source 
    Workbooks("book1").Activate
    ActiveWorkbook.VBProject.VBComponents("module1").Export ("c:\temp\mymod.bas")
    '// Output
    Workbooks("book2").Activate
    ActiveWorkbook.VBProject.VBComponents.Import ("c:\temp\mymod.bas")
End Sub

只支持索引0到4.您可以访问这些数组越界,并且作为该未定义行为的副作用,您将覆盖其他变量。

答案 1 :(得分:0)

我不确定你期望的*ptrTop的其他价值(超过六个);我们来看看deal

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

并且请记住,这是top的价值,在main中初始化:

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

因此,在deal中,您循环五次,递增card,然后在最后一次迭代中,for循环将第五次递增card,请参阅它是6,因为6 <= 5是假的,它会退出,如果你*ptrTop = card;*ptrTop确实一直等于六。