Pointers to Array Elements in C
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
int randomnumber;
char diceinput;
int slotnumber;
char lettertable[7];
char *character;
lettertable[1] = 'l';
lettertable[2] = 'r';
lettertable[3] = 't';
lettertable[4] = 'e';
lettertable[5] = 't';
lettertable[6] = 'e';
character = &lettertable[1];
printf("Please enter 'roll' to roll the dice. Enter 'exit' to quit the
game.\n");
scanf("%s", &diceinput);
if (strcmp(&diceinput, "exit")==0) {
printf("Now quitting. Thank you, and please play again!\n");
}
if (strcmp(&diceinput, "roll")==0) {
srand((unsigned)time(NULL));
randomnumber = rand() % 6 + 1;
printf("%d\n", randomnumber);
if (randomnumber >= 3) {
printf("Now enter 1 to obtain the corresponding letter from the
table.\n");
scanf("%d", &slotnumber);
if (slotnumber == 1) {
printf("%s", character);
}
}
}
}
I am trying to create a program that prints a random number whenever the
user enters "roll," and allows the user to enter "1" if the random number
is greater than or equal to 3. After the user enters "1" the program is
supposed to get the letter stored in the letter table[1], an element in
the array lettertable. However, when I run the program and enter "1",
instead of getting the letter "l", the output is a weird phrase: "lrtete"
with an upside down question mark. Can somebody please help me? Thank you.
***Please note that the code shown above is only a revelant section of the
unfinished program.
No comments:
Post a Comment