Click here to Skip to main content
15,885,101 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hello guys,
i'm a beginner, and wanted to make a program to generate random number's from a given set of numbers, ten times. i came up with this so far. i want it to generate a number from the array "numbers" but it generates numbers which r not in the declared array. i don't understand why?
please help me.


CSS
int numbers[] = { 3, 13, 22, 57, 417 };
int length = sizeof(numbers);
for (int aa=1;aa<=20;aa++)
    {cout <<numbers[rand()%length]<< endl;}



i you want to compile it for yourself and see, then here is the link to my entire code
link to my whole code
Posted

1 solution

C++
int length = sizeof(numbers) / sizeof(numbers[0]);

sizeof returns the size of the array in bytes and not the number of items in the array. Since this array contains integers that are 4 bytes one-by-one sizeof probably returns 5*4 so sometimes you read garbage from memory by overindexing the array.

In my codebase I follow a convention that is pretty practical. I refer to size of something in bytes with "size" while I refer to the number of items in a sequence (array or string or whatever) with "length". For example if I had an array class then I would name the method that returns the number of items as GetLength().
 
Share this answer
 
v4
Comments
H.Brydon 18-Aug-13 22:39pm    
Roses are red
Violets are blue
Your answer gets
a +5 for you
pasztorpisti 19-Aug-13 5:31am    
Thank you! This question was way too easy to harvest. I feel ashamed! :-)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900