gpt4 book ai didi

c - 如何从特定函数返回数组?

转载 作者:行者123 更新时间:2023-11-30 17:38:31 24 4
gpt4 key购买 nike

过去两天我一直在研究这个功能,但我似乎无法弄清楚。函数 displayBoard() 打开一个文本文件(在本例中为“board.txt”)并将其放入一维数组中。该代码是我的教授提供的。我将其变成一个函数并尝试返回数组 board[],以便我可以在 main 中操作它,但我无法做到这一点,我缺少什么?

void displayBoard ()
{
FILE *pInputFile; // file pointer
char board[64]; // the 8x8 board
int i=0; // loop counter
char inputFileName[] = "board.txt";

// Associate the actual file name with file pointer and try to open it
pInputFile = fopen(inputFileName, "r");
// Verify input file was found
if (pInputFile == NULL) {
printf("Attempt to open file %s failed. Exiting ... \n", inputFileName);
exit( -1);
}

// Read from the file into the board. Space in front of %c is important!
while (fscanf(pInputFile, " %c", &board[i]) != EOF) {
i++;
}

fclose(pInputFile); // close input file

// show contents of board
printf("Board is: ");
for (i=0; i<64; i++) {
if (i%8 == 0) {
printf("\n");
}
printf("%c ", board[ i]);
}

printf("\n\n");

return board;
}

int main ()
{
printf(" %s", board); // This is my printf statement to see if I am able to access
// board[] from the function
}

最佳答案

您需要通过声明函数使该方法返回 char *

char * displayBoard {
...
}

关于c - 如何从特定函数返回数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22110477/

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