[英]how can I pass the content of an array which is inside a struct to a function?
我有兩個函數,一個將文件的內容保存在一個名為“迷宮”的二維數組中,這個數組在一個結構中。 另一方面,第二個函數是為了將二維數組的內容打印到控制台中。
我的問題是第二個函數沒有打印結構內部二維數組的內容。 我相信是因為我沒有正確傳遞數組的內容,但我不確定。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* X and Y will be used to define the size of the maze*/
#define X 20
#define Y 40
typedef struct
{
char maze[X][Y]; /* X and Y have been defined as X = 20 and Y = 40*/
char robot;
int x,y;
}Cords;
這是我的函數原型:
void save_maze(Cords);
void print_maze(Cords);
將文件內容保存到二維數組中的函數:
void save_maze(Cords border)
{
int i,j,k,x,y;
char wall;
FILE *FileMaze;
FileMaze = fopen("maze.txt","r");
if (FileMaze == NULL)
{
printf("\n The file is missing");
}
else
{
printf("File was open! \n");
while(fscanf(FileMaze,"%d %d %c",&x,&y,&wall)!= EOF)
{
border.maze[x][y] = wall;
}
}
fclose(FileMaze);
printf("The Maze has been saved! \n");
}
應該打印二維數組的函數:
void print_maze(Cords border)
{
int i,j,k,x,y;
int row,col;
row=X;
col=Y;
for (i = 0; i <row ; i++)
{
for (j = 0; j < col; j++)
{
if(border.maze[i][j] != 'x' && border.maze[i][j] != 'o' && border.maze[i][j] != 'S' && border.maze[i][j] != 'E')
{
border.maze[i][j] = ' ';
}
else
{
printf("%2c",border.maze[i][j]);
}
}
printf("\n\r");
}
}
“print_maze”函數不打印結構內二維數組的內容。
看起來您正在嘗試按值而不是按引用將 struct Cords 傳遞給 print_maze 函數。 這意味着 print_maze 函數中的 border 參數是原始結構的副本,函數內部對 border 參數所做的任何更改都不會影響原始結構。
要解決此問題,您可以使用指針通過引用傳遞結構。 以下是修改函數簽名和函數調用的方法:
void save_maze(Cords* border);
void print_maze(Cords* border);
...
Cords border;
save_maze(&border);
print_maze(&border);
然后你需要使用->
而不是.
訪問函數內部結構的字段。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.