I will not comment on your code, that is already done. I'll anwer the original question instead. Blue Moon says "You can't", but you can if you wish. You can always do a sequential lookup in any table, if your list of values is terminated with what is called a sentinel value. That is a special value which is known in advance not to belong to the collection of normal data, and thus can be used to flag the end of the sequence, for instance a negative value if all normal data are known to be positive.
For a sequence of n
non-negative integers stored in an array of n+1
elements, we can store array[n]= -1
as a sentinel after populating the first n
elements with normal data. Then start at a random position in the data sequence and read until the end, with something like
// -- we assume pointer p is an initialized int* that
// satisfies the condition array <= p < array + n
// AND that array[n] is negative.
for( ; *p >= 0; ++p ){
// do something useful with *p
}
Terminating a sequence with a sentinel is a well known general technique and you'll find it in any book on algorithms. You can use it with arrays and with linked lists. In your case you must make sure that the element following the last element you wish to access in the array is a sentinel and that the random choice has not selected the sentinel (if n
is the length of the sequence, then rand() % n
will give you a correct offset; pointing to a sentinel would not harm, but the for
loop would terminate immediately). The size of the allocated array has to be at least n+1
, that is the maximum number of data elements you need, plus one for the sentinel.
By the way, in C the last element of an array is not array[size]
but array[size-1]
. There is no bounds checking on array access when bumping a pointer in C, that's up to you, as you will learn sooner or later from crashing programs. To get rid of confusion between pointers and referenced values you can read the instructive answers to "What exactly is a C pointer if not a memory address?", here at Stackoverflow.