Reputation: 41
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.
Upvotes: 3
Views: 64
Reputation: 41
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]);
}
}
}
}
Upvotes: 1