gpt4 book ai didi

c - 为什么将指针传递给不修改指针的函数后,指针的值会发生变化?

转载 作者:行者123 更新时间:2023-11-30 18:39:18 27 4
gpt4 key购买 nike

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)

当你有变量时,Card 会获取从 1 到 5 的索引

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

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

关于c - 为什么将指针传递给不修改指针的函数后,指针的值会发生变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30389652/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com