I have written a piece of code in C language in which I am initializing an array with random numbers/characters. But when I print the array values after initializing it, I see that value on every index is equal to last assigned value (value of last index). Kindly tell what is the problem in my 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 any key to continue . . .
You initialized all elements of elements of the array save
to the same pointer, so what you can see using any of them will be same.
In this case, I suggest you should store the data directly in save
like 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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.