2

Question: In my code, what ever I enter for n, compiler allows me to input and output only half of it. Why?

#include<stdio.h> 
#include<stdlib.h> 
int main()
{   
    int n; 
    scanf("%d\n",&n);   
    char *c= (char*)malloc((n+1)*sizeof(char));
    c[n]='\0';
    for(int i=0;i<n;i++)
    { 
        scanf("%c",&c[i]);
    }
    for(int i=0;i<n;i++)
    {
        printf("%c",c[i]);
    }
}
gsamaras
  • 71,951
  • 46
  • 188
  • 305
anik_1996
  • 31
  • 3

2 Answers2

2

Change this:

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

to this:

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

Sample output:

Georgioss-MacBook-Pro:~ gsamaras$ gcc -Wall main.c 
Georgioss-MacBook-Pro:~ gsamaras$ ./a.out 
5
a
b
c
d
e
abcde

I discuss the reasoning behind this solution in Caution when reading char with scanf (C).


PS: Do I cast the result of malloc? No!

Also since you dynamically allocated memory, do not forget to free() it at the end of your main(), like this:

free(c);
Community
  • 1
  • 1
gsamaras
  • 71,951
  • 46
  • 188
  • 305
1

Ques. compiler allows you to input only half of array size, Why?

Reason of problem :

scanf("%c",&c[i])          //Here %c takes enter key also as a part of input which reduces the input size to half.

So, there are mainly 2 solution to your problem:

Sol. 1 => you only need to include whitespace,rest code would be same.

scanf(" %c",c[i]) //use whitespace before %c

Sol. 2 => Don't enter one character at a time,please enter whole input as a bunch at once then press enter.

Shivam Sharma
  • 1,015
  • 11
  • 19
  • @ankit if you found any answer is worked for you & helful to understand your problem also..then you should accept that one ,so that community know the solution to this problem.. :) – Shivam Sharma May 20 '17 at 12:25