Noxter Noxter - 6 days ago 6
C Question

C - Issue with random number generator

I have an issue while generating a random number and giving the value to a pointer.

What I want to do here: generate a number between 1 and 1000, and the player will receive that amount of gold.
The base gold is 0 obviously.
Although, for some reason, when I printf the amount of integer gold, there were cases when it was more than 3000, which is obviously a sign of error.

The goldchange part is because the player will receive gold lots of times and I want it to work every time. Although at the moment, since I am testing this part of my program, the player receives gold only once.

Since I am a beginner programmer, I guess I am doing it wrong.
How should I do this correctly so integer GOLD will have the correct value?

int* gold=0;
int* goldchange;
srand(time(0));
goldchange=gold;
gold=gold+rand()%1000+1;
goldchange=gold-goldchange;
printf("You have received the following amount of gold: %d", goldchange);

printf("You have this many golds: %d", gold);


So, for example, this was what happened last time:
You have received the following amount of gold: 777
You have this many golds: 3108

But it should be 777 not 3108....
(obviously every run gives different numbers, but the two values are never the same...)

Answer

You are declaring to variables as pointers with:

int* gold=0;
int* goldchange;

And then proceeding to treat these as regular int variables. In the given code I see no reason for declaring these variables as pointers. Why not just

int gold=0;
int goldchange;
Comments