[英]C: How do I pass an array to a function?
I'm a beginner in C trying to make a Tic Tac Toe game.我是 C 的初学者,试图制作井字游戏。 So first I want to start off by displaying the board showing the available positions (0-8).
所以首先我想通过显示显示可用位置(0-8)的板开始。 Therefore I'm trying to pass all elements in
numArray
to board
so I can put each number in the board, but that's where I'm getting stuck as no numbers are being displayed.因此,我试图将
numArray
中的所有元素传递给board
,这样我就可以将每个数字放在板上,但这就是我卡住的地方,因为没有显示任何数字。
Would mean a lot if someone could help me out here:))如果有人可以在这里帮助我,那将意味着很多:))
Output: Output:
| |
---|---|---
| |
---|---|---
| |
[Player 1] Pick a number:
int main() {
int numArray[] = {0, 1, 2, 3, 4, 5, 6, 7, 8};
int playerOneCount = 0, playerTwoCount = 0;
board(numArray);
playerOne(numArray);
return 0;
}
void board(int array[]) {
printf(
" %c | %c | %c\n"
"---|---|---\n"
" %c | %c | %c\n"
"---|---|---\n"
" %c | %c | %c\n", array[0], array[1], array[2], array[3], array[4],
array[5], array[6], array[7], array[8]);
return;
}
Expected output:预期 output:
0 | 1 | 2
---|---|---
3 | 4 | 5
---|---|---
6 | 7 | 8
[Player 1] Pick a number:
Arrays aren't first-class values, which means they cannot be passed around like that. Arrays 不是一流的值,这意味着它们不能像那样传递。 You can, however, pass a pointer to the first element of the array, which will let you access the array in pretty much the same way:
但是,您可以将指针传递给数组的第一个元素,这将让您以几乎相同的方式访问数组:
int main (void) {
int numArray[] = {0, 1, 2, 3, 4, 5, 6, 7, 8};
// do whatever with the array
board(numArray);
// etc.
}
void board (int * arr) {
// here you can access the array elements directly, as in arr[3]
}
Note that you can write the function's parameter as int arr[]
;请注意,您可以将函数的参数写为
int arr[]
; this is completely equivalent to int * arr
, and I'd recommend getting familiarized with pointers if you haven't yet.这完全等同于
int * arr
,如果您还没有熟悉指针,我建议您熟悉一下。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.