c - Multidimensional Array Printing Gives Something Different -
#include <stdio.h> int main(int argc, char **argv) { int x[5][5] = {{0,1,2,3,4},{5,6,7,8,9}}; (int = 0; < 4; i++) { (int j = 0; < 4; i++) { printf("%d\n", x[i][j]); } } return 0; } this supposed give me: 0 1 2 3 4 5 6 7 8 9
and result is: 0 5 0 0
and then, when change them chars:
#include <stdio.h> int main(int argc, char **argv) { char x[5][5] = {{'0','1','2','3','4'},{'5','6','7','8','9'}}; (int = 0; < 4; i++) { (int j = 0; < 4; i++) { printf("%d\n", x[i][j]); } } return 0; } i 48 53 0 0.
why? code pretty clear me, seems happening obscure on background (or brain works in "pythonic" way...)
like @keith thompson said, didn't initialize 25 elements. remaining elements initialized 0. result, data stored way:
0 | 1 | 2 | 3 | 4 // row 0 5 | 6 | 7 | 8 | 9 // row 1 0 | 0 | 0 | 0 | 0 // row 2 0 | 0 | 0 | 0 | 0 // row 3 0 | 0 | 0 | 0 | 0 // row 4 you initialized first 2 rows of array. reason why got 0 5 0 0 output.
to correct output, need loop through first 2 rows of array.
steps fix :
first
you need change first for-loop from:
for (int = 0; < 4; i++) to
for (int = 0; < 2; i++) reason: because want loop through first 2 rows (row 0 , row 1).
second
you need change second for-loop from:
for (int j = 0; < 4; i++) to:
for (int j = 0; j < 5; j++) reason: need variable j loop condition, not i. need change 4 5; because in array, index starts 0. so, indexes of each columns 0,1,2,3,4 , respectively.
to sum up, code supposed be...
for (int = 0; < 2; i++) { (int j = 0; j < 5; j++) { printf("%d\n", x[i][j]); } } additionally, when changing char x[5][5], need use %c, print character, instead of %d.
moreover, reason getting weird numbers 48 because when print char %d, printing ascii values. referring ascii table below, number 48 represents character '0'.
image
Comments
Post a Comment