Reputation: 394
I made a number guessing game and want to print out all of the numbers that the user guessed while playing the game. However, when I run the program, it always prints out zero for all the values.
Your Tries: 0, 0, 0, 0, 0, %
It may be something wrong with the way I assigned the pointer value? Any help would be appreciated
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
int arr_size = 0;
int main()
{
// Initialize random number with seed 2021.
// Do not change this line, and do not call srand again.
srand(2022);
// the next line generate a random number between 1 to 100
int n = (rand() % 100) + 1;
int *p = malloc(sizeof(int) * arr_size);
while(1){
int guess;
scanf("%d", &guess);
arr_size ++;
p = realloc(p, sizeof(int) * arr_size);
p[arr_size-1] = guess;
if(n > guess){
printf("The Number is greater than %d\n", guess);
}else if(n < guess){
printf("The Number is less than %d\n", guess);
}else{
printf("You win. The Number is %d\n", guess);
break;
}
if(guess == -1){
printf("You input wrong number\nYou lose. The Number is %d", n);
break;
}
}
printf("Your Tries: ");
for(int i = 0; i < arr_size; i ++){
printf("%d, ", p[arr_size]);
}
return 0;
}
Upvotes: 0
Views: 105
Reputation: 213678
int *p = malloc(sizeof(int) * arr_size);
Allocating zero bytes isn't safe, the compiler can either return a null pointer or a pointer pointing at weird stuff, which may or may not be realloc
atable(?). Replace this with int *p = NULL;
to get deterministic, portable behavior instead.
p = realloc(p, sizeof(int) * arr_size);
There is no guarantee that p
is pointing at the reallocated data after this. Correct use of realloc is:
int* tmp = realloc(p, sizeof(int) * arr_size);
if(tmp == NULL) { /* handle errors */ }
p = tmp;
You never free(p)
.
There is no need to use dynamic allocation to begin with here, all you achieve with it is needless complexity, bloat and a much slower program. Just use int p[100];
and watch all your problems go away, while at the same time massively improving execution speed.
printf("%d, ", p[arr_size]);
is nonsense and out of bounds, use p[i]
.
Upvotes: 1