0

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]. 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:

#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;
}
4
  • 1
    Valid array indexes will be from 0 to 4 for both dimensions of arrayPrimary so you are invoking undefined behavior by accessing index 5. Commented Dec 28, 2013 at 19:05
  • Where is <stdio.h> and <time.h> header? Commented Dec 28, 2013 at 19:05
  • I have both headers in my code I just forgot to copy them over. Commented Dec 28, 2013 at 19:09
  • 1
    Why are you bending yourself into a pretzel setting the values? What's wrong with arrayPrimary[x][y] = rand() % 10? Commented Dec 28, 2013 at 19:17

1 Answer 1

2

In C, array indexing starts from 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++)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.