printf prints unexpected last element of a multidimensional array in C, depending on input? -


i'm learning use multidimensional arrays in c , i'm unable understand why printf() gives unexpected result in following program.

the idea in program wish initialize 5x2 array , accept 5 integers user scanf populate 2nd index, print array:

#include <stdio.h> #include <conio.h>  int main(void) {     int i=0, mat[5][2] = {         {0, 0},         {0, 0},         {0, 0},         {0, 0},         {0, 0}     };      printf("please enter 5 integers press enter: \n");      {         scanf("%i", &mat[i][2]);         i++;         } while (getchar() != '\n');       printf("here's 5x2 array looks like: \n");      for(i = 0; < 5; i++){         printf("%i %i", mat[i][1], mat[i][2]);         printf(" \n");     }      return 0;    } 

if enter integers user, output expected:

c:\users\hackr>tmp.exe please enter 5 integers press enter: 0 1 2 3 4 here's 5x2 array looks like: 0 0 0 1 0 2 0 3 0 4 

however, if enter different integers, last line of output not expected:

c:\users\hackr>tmp.exe please enter 5 integers press enter: 1 2 3 4 5 here's 5x2 array looks like: 0 1 0 2 0 3 0 4 0 4  c:\users\hackr>tmp.exe please enter 5 integers press enter: 9 8 7 6 5 here's 5x2 array looks like: 0 9 0 8 0 7 0 6 0 4 

in fact, can see above, looks final element of index 2 arbitrarily "4".

perhaps due misunderstanding on part regarding how array values indexed or referenced?

always array starts index 0.

you can try following snippet of code:

#include <stdio.h> #include <conio.h>  int main(void) {     int i=0, mat[5][2] = {         {0, 0},         {0, 0},         {0, 0},         {0, 0},         {0, 0}     };      printf("please enter 5 integers press enter: \n");      {         scanf("%i", &mat[i][1]);         i++;         } while (getchar() != '\n');       printf("here's 5x2 array looks like: \n");      for(i = 0; < 5; i++){         printf("%i %i", mat[i][0], mat[i][1]);         printf(" \n");     }      return 0;    } 

while declaration can use mat[5][2], access should use

mat[0][0] mat[0][1] mat[1][0] mat[1][1] ... .. mat[4][0] mat[4][1] 

i think should work.


Comments

Popular posts from this blog

Java 3D LWJGL collision -

spring - SubProtocolWebSocketHandler - No handlers -

methods - python can't use function in submodule -