2017-10-14 39 views
3

访问2D阵列值我需要从stdin采取2D阵列(网格),做一些manupulation到字符和打印带的变化的新的网格。使用指针

我的策略是使一个STRUC与电网格[LINES] [COLUMNS]然后使用的getchar()来使用指针的每个字符推入电网。它工作的伟大,当我在函数中打印,但我不能从外部存取权限的值。我只会得到可能代表内存地址的奇怪字符。

下面是程序的简化代码块。

#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

我传递等事情到了这个结构在实际的程序和我没有任何ISSU进入电影为int和焦炭的infomration。我唯一遇到的问题是2D阵列。另一件事,我不能用这个maloc。

+0

固定谢谢@兴 – CareFace

+0

好的。对不起,这是我第一次使用stackoverflow。 – CareFace

回答

1

改变了,而到如果使我的for循环影响并网>盒[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]);  
     } 
    } 
    } 
}