Introduction to Algorithm Competition Classics (7) – Two-Dimensional Character Arrays

Words: 244

When working on the problem 【UVa】[227]Puzzle1
I discussed variables of the form char map[5][5] ; again
(Article URL: 【UVa】[227]Puzzle)

That is, the issue of understanding map[5][5]

s[5] can be understood as a string (character array)
then map[5][5] can also be understood as a multi-line string (two-dimensional character array)

abc (0)
def (1)
ghi (2)

map[0] then represents “abc”
map[1] then represents “def”
map[2] then represents “ghi”

That is, map[n][m]
n is the row number, m is the column number

map[0][0]==’a’
map[0][1]==’b’
map[1][1]==’e’
map[2][0]==’g’

So to assign values to map[5][5], you can use

cpp
1
2
3
char map[5][5];
for(int i=0;i<5;i++)
scanf("%s",map[i]);

Similarly, it can be used for printf("%s",map[i]);
Testing shows it cannot!!
It should be because printf only ends when it encounters ’\0’
And after the first line, garbled characters follow it
The output after using it is as follows

But using a nested loop together with putchar(map[i][j]);
or printf("%c",map[i][j]);
it can output normally. The code is as follows

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
#include<stdio.h>
#include<string.h>
int main() {
    char map[5][5];
    memset(map,0,sizeof(map));
    for(int i=0; i<5; i++)
        scanf("%s",map[i]);
    for(int i=0; i<5; i++) {
        for(int j=0; j<5; j++) {
//          putchar(map[i][j]);
            printf("%c",map[i][j]);
        }
        printf("\n");
    }
    return 0;
}

From this it can be seen
the charm of C goes far beyond this -.-
Also, once again I sigh at how good the exercises in this book are

Loading...