Home > OS >  how can I pass the content of an array which is inside a struct to a function?
how can I pass the content of an array which is inside a struct to a function?

Time:12-23

I have two functions, one saves the content of a file in a 2d array called "maze", this array is inside a struct. On the other hand, the second function is meant to print the content of that 2d array into the console.

My problem is that the second function is not printing the content of that 2d array that is inside the struct. I believe is because I am not passing the content of the array correctly but I am not sure.

#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;

This are my function prototypes:

void save_maze(Cords); 
void print_maze(Cords);

Function that saves the file content into the 2d array:

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");
    
}

Function That should print the 2d array:

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(",",border.maze[i][j]);
            }
        }
        printf("\n\r");
    }   
}

The "print_maze" function does not print the content of the 2d array which is inside the struct.

CodePudding user response:

It looks like you are trying to pass the struct Cords to the print_maze function by value, instead of by reference. This means that the border parameter in the print_maze function is a copy of the original struct, and any changes made to the border parameter inside the function will not affect the original struct.

To fix this, you can pass the struct by reference using a pointer. Here is how you can modify the function signature and the calls to the function:

void save_maze(Cords* border); 
void print_maze(Cords* border);
    
...
    
Cords border;
save_maze(&border);
print_maze(&border);

Then you'll need to use -> instead of . to access the fields of the struct inside the functions.

  • Related