My array is not working..

bouzigue's Avatar, Join Date: Oct 2011
Light Poster
my program generate numbers but it does not store it in the array.. what function must i include..
Code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int rndm_array [10];
     
int main(int argc, char *argv[])
{
    unsigned int iseed = (unsigned int)time(NULL);
    srand (iseed);

     int i,idx;
      for (i=1; i<7; i++)
      printf ("Number[%d]= %u\n",
      i, rand () % 40+1,&rndm_array[idx]);
      {
       rndm_array [idx] = i, rand () % 40+1;
      }
      
      for (i=1; i<7; i++)
        {
          printf("\nrandom_array [%d]=",i, rand()%40+1);
          printf("%d\n", rand()%40+1);
        }
  system("PAUSE");
  return 0;
}
0
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
You're displaying the contents of rndm_array[idx] before you assign it a value. Also lookup the comma operator, because the code "rndm_array[idx]=i, rand()%40+1" might not do what you think it's going to do.
0
bouzigue's Avatar, Join Date: Oct 2011
Light Poster
in fact, m program is to generate 6 random numbers, zen store the results in the array so that the next the regenerated numbers can be compared to the previous one..
0
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
What output do you get, and what output did you expect?
0
bouzigue's Avatar, Join Date: Oct 2011
Light Poster
i did get the generated random numbers but the array did not keep record of any previous generated numbers... it generate some kind of random numbers by itself..
0
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
Well I can't help if you won't answer my questions.
0
bouzigue's Avatar, Join Date: Oct 2011
Light Poster
Number[1]=27
Number[2]=9
Number[3]=27
Number[4]=6
Number[5]=19
Number[6]=12

random_array[1]=14

random_array[2]=19

random_array[3]=12

random_array[4]=35

random_array[5]=4

random_array[6]=194
0
bouzigue's Avatar, Join Date: Oct 2011
Light Poster
last one is 19..
0
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
Your first printf has too many parameters.
Code:
printf ("Number[%d]= %u\n",
      i, rand () % 40+1,&rndm_array[idx]);
%d prints i, %u prints rand()%40+1, and nothing displays &rndm_array[idx].

You do that in a loop, 7 times, then after the loop ends there is an open brace, and you do
Code:
rndm_array [idx] = i, rand () % 40+1;
which is equivalent to
Code:
rndm_array [idx] = i;
because of the way the comma operator works. This writes the number 8, which is the current value of i, to an undefined location in memory (because idx is undefined) and therefore your program exhibits Undefined Behaviour - the most difficult to find bug of all.

The next loop performs:
Code:
printf("\nrandom_array [%d]=",i, rand()%40+1);
which doesn't access rndm_array at all.