Raju Gadju
Raju Gadju

Reputation: 21

Unexpected output when trying to print user input through arrays

This code takes in user input into an array and then prints it. Every time I print the user input a random extra character is printed at the end.

#include <stdio.h>
#include <ctype.h>

int main(void) 
{
    char arr[100]; 
    char c;
    printf("Enter a Sentence:");
    int i =0;
    for (i = 0;(c = getchar()) != '\n';++i)
        arr[i] = c;
    arr[++i] = '\n';
    for (int i = 0;arr[i] != '\n';++i)
        putchar(arr[i]);
}

For example I expected the output of

Enter a sentence:abc

to be abc but instead I got abcu.

Upvotes: 1

Views: 59

Answers (4)

user3629249
user3629249

Reputation: 16540

Regarding:

arr[++i] = '\n';

This is incrementing i before assigning '\n', so arr[++i] points an extra character into the array.

That is why an unexpected character is being printed.

If you replace that statement with:

arr[i] = '\n';

your code should work.

Upvotes: 1

S.S. Anne
S.S. Anne

Reputation: 15566

This:

for (i = 0;(c = getchar()) != '\n';++i)
    arr[i] = c;
arr[++i] = '\n'; /* here */

should be this:

for (i = 0;(c = getchar()) != '\n' && i < 100;++i)
    arr[i] = c;
arr[i] = '\n'; /* here */

You're skipping one character of the buffer, as i had been incremented already at the end of the previous loop. This reads uninitialized data from the buffer (presumably originating from the stack).

You're also not stopping past the end of the buffer, which could cause buffer overflow.

Along with that, you should probably initialize the array with this:

char arr[100] = { '\0' };

Upvotes: 1

Achal
Achal

Reputation: 11921

Change this

arr[++i] = '\n'; /* this skips the current a[i] & put \n into next position which is incorrect */

to

arr[i] = '\n';

as the variable i already incremented in condition part of for loop here

for (i = 0;(c = getchar()) != '\n';++i /* before loop terminating i incremented here */) {
     arr[i] = c;
 }

Also its good to initialize the buffer while declaring itself to avoid getting some junk value. For e.g

char arr[100] = {}; /* zerod whole array */

And also make sure this (c = getchar()) != '\n' doesn't happen >100 times else buffer overflow happens which cause undefined behavior. One possible way is

for (i = 0; i < sizeof(arr)-1 && (c = getchar()) != '\n';++i) {
     arr[i] = c;
}

Upvotes: 3

hmakholm left over Monica
hmakholm left over Monica

Reputation: 23332

When you read the newline, i has just been increased to 3 by the update expression in the first for loop.

Then arr[++i] = '\n' increases i to 4 and assigns to arr[4]. Nothing ever gets assigned to arr[3], but it appears that this location happened to contain an u when the array was allocated from the stack.

Upvotes: 0

Related Questions