-1

I'm trying to get randomly a number from an array, so, I did it like this:

srand(time(NULL));
const char numbers[19] ={506001, 506002, 506003, 506004, 506005, 506006, 506007, 506008, 506009, 506010, 506011, 506012, 506013, 506014, 506015, 506016, 506017, 506018, 506019};
printf("%i",(int)numbers[rand() % 19]);
printf("\n");

But instead of giving me a number from the array it prints any other value in negative. Output

Also, With numbers that are short than 3 digits it works fine, the problem starts when I use 3 or more digits numbers. What am I doing bad?

Derezzed
  • 1,093
  • 3
  • 11
  • 15
  • `char` is one byte. Are you using one of those 32-bit byte systems? By the way, `char` already gets converted to `int` when going into an ellipsis (like `printf`'s). – chris Dec 27 '13 at 20:25
  • 1
    The screenshot is a large chunk of no information. Consider removing it. While you are at it, decide which language you are using. – n. m. could be an AI Dec 27 '13 at 20:29

3 Answers3

3

Change

const char numbers[19] ...

to

const long numbers[19] ...

A char is 1 byte (8 bits at least for most modern machines). Your numbers are too large for a char.
The size of the long (it looks like you have a Windows system) is at least 32 bits.

Community
  • 1
  • 1
FuzzyBunnySlippers
  • 3,387
  • 2
  • 18
  • 28
1

You have a const char numbers[19], ie. 19 const (signed) char's. A signed char can only hold values from -128 to +127, any other numbers are not possible. Use const int numbers[19].

haccks
  • 104,019
  • 25
  • 176
  • 264
deviantfan
  • 11,268
  • 3
  • 32
  • 49
  • 1
    `char` can be signed or unsigned and can sometimes store a higher range than that. – chris Dec 27 '13 at 20:28
  • In his case, it´s clearly signed, but thanks for remembering me of the range thing. I got too used to "normal" machines... – deviantfan Dec 27 '13 at 20:30
  • @deviantfan There are also not "normal" machines that have a `INT_MAX` of 32767. Common in the embedded world of 2013. Better to use `long` for values like 506001 to 506019. – chux - Reinstate Monica Dec 27 '13 at 20:47
0

You're putting integers into a character array. You probably want:

const long numbers[19] ={506001, 506002, 506003, 506004, 506005, 506006, 506007, 506008, 506009, 506010, 506011, 506012, 506013, 506014, 506015, 506016, 506017, 506018, 506019};
Eric
  • 843
  • 6
  • 15