3

I need to take a 2d array (Grid) from stdin, do some manupulation to the chars and print a new grid with the changes.

My strategy was to make a Struc with a Grid grid[LINES][COLUMNS] then use getChar() to push each char into grid using a pointer. It work great when I print within the function but I can't acces the values from outside. I am only getting weird characters that probably represent memory adress or something.

Here is a simplified code block of the program.

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>

struct Grid{                          
    char box[20][40]; 
};


int main(int argc, char *argv[]) {
    struct Grid grid;

    readInitGrid(&grid);
    displayGrid(&grid);

}

void readInitGrid(struct Grid *grid) {
  char c;
  for (unsigned int i = 0; i < 20; i++) {
    for (unsigned int j = 0; j < 40 + 1; j++) { //+1 is for the /n at the end of each line
      while ((c = getchar()) != EOF) {
        grid->box[i][j] = c;
        printf("%c", grid->box[i][j]);     //Will print correcly
      }
    }
  }
}

void displayGrid(const struct Grid *grid) {
  for (unsigned int i = 0; i < 20; ++i) {
      for (unsigned int j = 0; j < 40; ++j) {
          printf("%c", grid.box[i][j]);       //This do not work
      }
  }
  printf("\n");
}

Result - See both print block bellow First block show perfectly but second is messed-up

I am passing other things to this struct in the real program and I dont have any issu to acces the infomration for int and char. THe only one I am having issue with is 2d array. An other thing, I can't use maloc for this.

2
  • Fixed Thank you @xing Commented Oct 14, 2017 at 23:13
  • Ok did it. Sorry it is my first time using stackoverflow. Commented Oct 15, 2017 at 19:13

1 Answer 1

1

Changed the while to an if so that my for loop affect the grid->box[i][j] = c;

void readInitGrid(struct Grid *grid) {
  char c;
  for (unsigned int i = 0; i < 20; i++) {
    for (unsigned int j = 0; j < 40 + 1; j++) { 
      if ((c = getchar()) != EOF) {
        grid->box[i][j] = c;
        printf("%c", grid->box[i][j]);    
      }
    }
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.