c - array values not same after initializing -
i have written piece of code in c language in initializing array random numbers/characters. when print array values after initializing it, see value on every index equal last assigned value (value of last index). kindly tell problem in code?
code:
#include <stdio.h> #include <stdlib.h> #include <time.h> int main () { char *save[3][3] = { {" "," "," "}, {" "," "," "}, {" "," "," "} }; char x[2] = {'\0', '\0'}; int i, j, b; srand(time(null)); printf("assigned values (initializing):\n"); for(i=0; i<3; i++) { for(j=0; j<3; j++) { b = rand()%10; x[0] = b+'0'; save[i][j] = x; printf("%s ",save[i][j]); } } printf("\n\nvalues after initializing:\n"); for(i=0; i<3; i++) { for(j=0; j<3; j++) { printf("%s ",save[i][j]); } } printf("\n\n"); return 0; }
output:
assigned values (initializing): 1 5 9 8 5 7 5 4 1 values after initializing: 1 1 1 1 1 1 1 1 1 press key continue . . .
you initialized elements of elements of array save
same pointer, can see using of them same.
in case, suggest should store data directly in save
this:
#include <stdio.h> #include <stdlib.h> #include <time.h> int main (void) { char save[3][3][2] = { {" "," "," "}, {" "," "," "}, {" "," "," "} }; int i, j, b; srand(time(null)); printf("assigned values (initializing):\n"); for(i=0; i<3; i++) { for(j=0; j<3; j++) { b = rand()%10; save[i][j][0] = b+'0'; printf("%s ",save[i][j]); } } printf("\n\nvalues after initializing:\n"); for(i=0; i<3; i++) { for(j=0; j<3; j++) { printf("%s ",save[i][j]); } } printf("\n\n"); return 0; }
Comments
Post a Comment