0

I have a random number generator feeding numbers into an array, but when I print out the table, the last line is always a set of values out of the boundaries that I defined in the following function:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int temp[22];
    int n;
    for(n=0; n<23; n++){
        temp[n] = rand()%(100 + 1 - 60) + 60;
        printf("%d  ,  %d \n", n, temp[n]);
}
return 0;

Ive created something of this nature before, but now its acting up, I just dont know where.

Mr Veritas
  • 47
  • 3
  • 4
    `for(n=0; n<23; n++)` -> `for(n=0; n<22; n++)` – George Mar 24 '17 at 17:56
  • Funny. The last iteration probably overwrites `n` in the 1st statement, and then the access of `temp[n]` in the next line accesses some random location (UB). – Paul Ogilvie Mar 24 '17 at 18:00
  • [What does your step debugger tell you?](http://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) –  Mar 24 '17 at 18:04
  • @JarrodRoberson I'm sorry, Is there something you could not understand about my question? I appreciate the suggestion though. – Mr Veritas Mar 24 '17 at 18:10

2 Answers2

3

You are accessing the array outside the bounds which is undefined behaviour.

Instead make use of sizeof operator to avoid such problems:

for(n = 0; n < sizeof temp/sizeof temp[0]; n++)

But note that if temp were to be an malloc'ed pointer (int *temp = malloc(23 * sizeof *temp);) then sizeof wouldn't work.

P.P
  • 117,907
  • 20
  • 175
  • 238
2

Your array is being accessed outside of its bounds.

int temp[22]; 

This declaration assigns 22 indices to temp, temp[0] is the first value and temp[21] is the last value you can access in your array. Counting 0, from 0..21 = we have 22 values


Your for loop is incorrect:

for(n=0; n<23; n++)

This will make the program attempt to access temp[22], which doesn't exist. You need to change it to:

for(n=0; n<22; n++)

Furthermore: return 0; needs to be inside and at the end of your main() function. It's possibly a typo, but you're missing a closing brace } in your main() function, at least how you posted it.

Santiago Varela
  • 2,199
  • 16
  • 22
  • not the dv, but "return 0; needs to be inside and at the end of your main() function," is not strictly true. – George Mar 24 '17 at 18:07
  • @George it's not necessary, but as it currently stands, there's global **return 0** there, which is incorrect. The main function isn't being closed. – Santiago Varela Mar 24 '17 at 18:09