There are many things wrong.
> char* buffer = malloc(5);
> buffer[5] = '\0';
This is an array overrun, the \0 you place is outside the memory you allocated.
The code is riddled with the magic numbers 4 and 5.
How many actual code values are you trying to compare?
Start by having
#define MAX_CODE_LEN 5
Then replace all the literal 4 & 5 with that symbol.
> for(printAnswer = 0; printAnswer <= 4; printAnswer++)
> for (getAnswer = 0; getAnswer < 5; getAnswer++)
Both these loop the same number of times, but are written in two different ways.
Both should be like
for(printAnswer = 0; printAnswer < MAX_CODE_LEN ; printAnswer++)
for (getAnswer = 0; getAnswer < MAX_CODE_LEN ; getAnswer++)
> read(0, buffer, 5);
Bear in mind that you'll end up storing the newline character at some point.
Do you allow for this in your buffer length?
> int correctPlace=0;
> int correctDigit=0;
These should surely be reset to zero on each attempt.
> for (getAnswer = 0; getAnswer <=4; getAnswer++)
> //scanf("%d", &answer[getAnswer]);
> answer = input();
You should stick with the scanf.
Before you get to input and randomised secrets, you need to make sure you have a reliable function to check the answers.
Here is an exercise for you.
Code:
#include <stdio.h>
#include <stdlib.h>
#define MAX_CODE_LEN 5
// This performs the following step
// the game indicates to the player the number of well placed pieces and the number of misplaced pieces.
void checkAnswer(char guess[], char secret[], int len, int *hits, int *miss) {
*hits = 0;
*miss = 0;
for ( int i = 0 ; i < len ; i++ ) {
if ( guess[i] == secret[i] )
// over to you
}
}
void testCheckAnswer(void) {
char secret[MAX_CODE_LEN+1] = "32123";
char tests[][MAX_CODE_LEN+1] = {
"12345", // 1 hit, 2 miss
"54321", // 1 hit, 2 miss
"56789", // 0 hit, 0 miss
"32123", // 5 hit, 0 miss - the winner
"23312", // 0 hit, 5 miss
"11111",
"22222",
"33333",
// add any other cases you can think of
"" //!! end this with an empty string
};
// run tests until the empty string
for ( int test = 0 ; tests[test][0] != '\0' ; test++ ) {
int hit = 0, miss = 0;
checkAnswer(tests[test], secret, MAX_CODE_LEN, &hit, &miss);
printf("Guess=%s, secret=%s: hits=%d, miss=%d\n",
tests[test], secret, hit, miss);
}
}
int main ( ) {
testCheckAnswer();
}
Having done that, your first simple game main is very easy
Code:
int main ( ) {
char secret[MAX_CODE_LEN+1] = "32123";
char guess[MAX_CODE_LEN+1];
bool won = false;
for ( tries = 0 ; tries < 10 && !won ; tries++ ) {
printf("Enter your guess of %d chars\n",MAX_CODE_LEN);
scanf("%s",guess);
int hit = 0, miss = 0;
checkAnswer(guess, secret, MAX_CODE_LEN, &hit, &miss);
printf("You have %d correct guesses and %d incorrect guesses\n",
hit, miss);
won = hit == MAX_CODE_LEN;
}
if ( won ) {
printf("Congratulations\n";
} else {
printf("Better luck next time\n");
}
}