[英]Inputting random numbers into an array
I tried to create an array and fill it with random numbers using rand(), and it would seem that I got the code to work but when I return the data to the screen it all appears to be correct except in value arrayPrimary[5][2]
. 我尝试使用rand()创建一个数组并用随机数填充它,似乎我得到了代码,但是当我将数据返回到屏幕时,除了值
arrayPrimary[5][2]
之外,它们似乎都是正确的。 arrayPrimary[5][2]
。 It just shows a garbage value and I cant seem to figure out why it would do that in only this spot. 它只是显示了一个垃圾值,我似乎无法弄清楚为什么它会只在这个位置做到这一点。 I'm still new to learning the C language so please be as descriptive as possible to help me understand:
我还是学习C语言的新手,所以请尽可能描述,以帮助我理解:
#include <stdlib.h>
main ()
{
srand (time(NULL));
int arrayPrimary[5][5];
int x,y,a,b;
for(x=1; x<6; x++)
{
for (y=1; y<6; y++)
{
int *z= &arrayPrimary[x][y];
*z=rand() %10;
}
}
for(a=1; a<6; a++)
{
for(b=1; b<6;b++)
{
printf ("The current value of [%d][%d] is:%d\n",a,b,arrayPrimary[a][b]);
}
}
return 0;
}
In C, array indexing starts from 0
. 在C中,数组索引从
0
开始。
Change 更改
for(a=1; a<6; a++)
{
for(b=1; b<6;b++)
to 至
for(a=0; a<5; a++)
{
for(b=0; b<5;b++)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.