Reputation: 167
I wanna write a program that translates a message entered by the user into B1FF-speak. However, the program seems to crash here:
#define MAX_LEN 80
char message[MAX_LEN];
printf("Enter a message: ");
for (int i = 0; i < MAX_LEN - 1; i++)
scanf("%c", message[i]);
for (int i = 0; i < MAX_LEN - 1; i++)
printf("%c", message[i]);
Where is the mistake? I can't seem to find it. I wanna understand why this specific piece of code crashes my program.
Thanks in advance.
Upvotes: 0
Views: 55
Reputation: 445
The problem is that you are expected to pass a pointer to scanf. Normally you pass an array (which is a pointer), or a char-pointer (string). What you are doing is passing the char itself. The method has no possibility to write something into the char, because it is copied before the function call.
What happens then is that the method interprets the uninitialized char as an address and tries to write to a random location which most likely fails.
Simply pass the address of the char:
char message[MAX_LEN];
printf("Enter a message: ");
for (int i = 0; i < MAX_LEN - 1; i++)
scanf("%c", &message[i]);
for (int i = 0; i < MAX_LEN - 1; i++)
printf("%c", message[i]);
Upvotes: 0
Reputation: 607
You need to add an ampersand in the scanf statement.
scanf("%c", &message[i]);
Upvotes: 1