我用C语言编写了一段代码,其中我用随机数字/字符初始化一个数组。但是当我在初始化之后打印数组值时,我看到每个索引上的值等于最后指定的值(最后一个索引的值)。请告诉我代码中的问题是什么?
代码:
#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;
}
输出:
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 . . .
答案 0 :(得分:5)
您已将数组save
的所有元素元素初始化为同一指针,因此您可以使用其中任何一个元素看到的内容都是相同的。
在这种情况下,我建议您应该将数据直接存储在save
中,如下所示:
#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;
}