In my cursory look at your code, I see a few issues. The first is the use of so many global variables. I understand they are needed on occasion but at the least, given them descriptive names that are longer than two letters. When I use a global variable I also give it a capitalized first letter and I do this only for global variables so it is easy to distinguish them.
The second thing is your use of the function
srand
. The pseudo-random number generator should be seeded only one time so that call should be moved into the
main
function as one of the first things it does. The calls to
rand
are OK as they are.
I also wonder about how you use the integer arrays. You are re-allocating them and initializing them with values of zero every time through the loop. Are you sure they get set correctly? It appears to me that
prevx
and
prevy
are always set to the values of the first items but those are always zero. Is that really the behavior you want?
If I were you I would allocate those two arrays just once and their size would be the maximum they could ever be. Then a length value should be maintained and used which you already have -
body
. This way, the data is persistent and never cleared. Your logic will need to change to simulate movement but I think this is a better way to go with the code.
One more thing - the literal values 21 and 51 should appear only once. Since this is C, I would add those two as definitions and then use the definitions instead of those numbers. Here is an example :
#define HEIGHT 51
#define WIDTH 21
and then
xf = rand() % WIDTH;
yf = rand() % HEIGHT;