为了保持简短,我遇到了一个问题,它让我改变了一个预构建的程序以包含指针。
这是一副纸牌和两只手。
我正在(尝试)做到这一点,而不是复制牌组的值并将它们放入手中,我只会让手指向牌组中的牌。我知道这并不是真正的甲板工作方式,但练习的重点只是习惯指针,而不是它的实用性(程序实际设置甲板的方式让我想撕掉我的头发)。
我几乎掌握了将 Ptr 设置到牌组顶部内存的基本语法,然后将其存储到手中。
但是,当我有手阵时,问题就来了。这只手不等于牌组内存,它是下一个可用内存,但它仍然具有相同的值,这意味着我没有指向它,我正在复制它。
这是原型(prototype)函数
int dealHand(int wDeck[][FACES], int *wHand[HAND], int top);
下面是定义和来自 main
的调用:
int *hand1[HAND] = {0};
int topDeck = 1;
topDeck = dealHand(deck, hand1, topDeck);
函数如下:
int dealHand(int wDeck[][FACES], int *wHand[HAND], int top) {
size_t hand;
size_t row;
size_t col;
int *arrayPtr;
for (hand = 0; hand < HAND; hand++) {
for (row = 0; row < SUITS; row++) {
for(col = 0; col < FACES; col++) {
if (wDeck[row][col] == top) {
printf("%d %d\n", row, col);
arrayPtr = &(wDeck[row][col]);
wHand[hand] = arrayPtr;
printf(" DECK: %p\n", &wDeck[row][col]);
printf(" DECK: %d\n", wDeck[row][col]);
printf("POINTER: %p\n", arrayPtr);
printf("POINTER: %d\n", *arrayPtr);
printf(" HAND: %p\n", &wHand[hand]);
printf(" HAND: %d\n", wHand[hand]);
} // if
} // row
} // col
top++;
} // hand
return top;
}
最佳答案
为了存储指针,wHand
数组必须是指针数组:
// wDeck is a 2-dimensional array of ints.
// wHand is an array of pointers to ints.
void dealHand(int wDeck[][FACES], int *wHand[HAND]) {
wHand
数组的大小为HAND
,因此其索引从0
到HAND - 1
。 for
循环访问wHand[HAND]
是错误的:
for (hand = 0; hand <= HAND; hand++) // Error: should be 0 to HAND-1.
arrayPtr
是指向wDeck
数组的指针,因此它必须包含元素的地址:
arrayPtr = &(wDeck[row][col]); // Parens are optional.
然后应该将地址复制到 wHand
数组中,该数组现在包含指针,而不是 int
:
wHand[hand] = arrayPtr;
请注意,通常引用数组时不带括号:
name[i][j]
而不是 (name)[i][j]
:
printf(" DECK: %p\n", &wDeck[row][col]);
printf(" DECK: %d\n", wDeck[row][col]);
// Similarly for printing the HAND data.
编辑:
既然您已将 wHand[]
数组更改为包含指针,您还需要更新打印其值的方式:
printf(" HAND: %p\n", wHand[hand]); // Each element is a pointer.
printf(" HAND: %d\n", *wHand[hand]); // Print the int it points to.
关于c - 使数组指向另一个数组的内存 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23162198/