Shuster
Shuster

Reputation: 167

C: Let the user fill a char array one character by one. Then print it

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

Answers (3)

birdfreeyahoo
birdfreeyahoo

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

abdev
abdev

Reputation: 607

You need to add an ampersand in the scanf statement.

scanf("%c", &message[i]);

Upvotes: 1

OznOg
OznOg

Reputation: 4732

you need to pass the address to scanf:

scanf("%c", &message[i]);

Upvotes: 0

Related Questions