C Programming - Input / Output - Discussion

Discussion Forum : Input / Output - Point Out Errors (Q.No. 2)
2.
Point out the error in the program?
#include<stdio.h>

int main()
{
    char ch;
    int i;
    scanf("%c", &i);
    scanf("%d", &ch);
    printf("%c %d", ch, i);
    return 0;
}
Error: suspicious char to in conversion in scanf()
Error: we may not get input for second scanf() statement
No error
None of above
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
23 comments Page 2 of 3.

Sowmiya said:   8 years ago
The 'i' is an integer type. So %d should be used and 'ch' is a character type so %c or %s should be used.

Ivon said:   9 years ago
But why I use CodeBlock (GCC compiler) to get it compiled and each scan runs smoothly, just getting wrong value, but it just got value for each place!

Shivam said:   9 years ago
Nice question!

[B]. Error: We MAY not get input for second scanf() statement.

"may".

-If you enter a character for first scanf, you are allowed to enter a value for second scanf.

-If you enter an integer for first scanf, you are not allowed to enter a value for second scanf.

Answer is simple just try think harder in memory size differences between int and char :).

Shivi said:   1 decade ago
Because %d is a format specifier of int type but ch is a char data type.

Dinesh said:   1 decade ago
I executed this program in Dev c++.

int main()
{
char i;
scanf("%d",&i);
printf("i==%c",i);
getch();
return 0;
}

Program compiled and executed successfully (Without any warning and errors).

Input provided : 65
Output : i==A

Nilay Vishwakarma said:   1 decade ago
@Khushi.
There can't be any segmentation fault in this program
ch would store ASCII 10 (return or line feed).

Try cleaning buffer before entering next value since <return> would be in buffer and gets stored in next scanf.

@Himanshu Bansal.
Your point is almost correct, theoretically. However,we can store integer value inside character value, but there would be a slight ,malfunction. The least significant bits of the integer would be accepted as character.

@Rup.
The apple has fallen very far dude.

Himanshu Bansal said:   1 decade ago
You can store the character value inside integer value because character is of 1 byte and integer is 2 byte but you can not store integer value inside character value.

Rup said:   1 decade ago
'i' is an integer type so %d should be used and 'ch' is a character type so %c or %s should be used.

Shoana Carvalho said:   1 decade ago
What I guess is segmentation fault occurs only when there is buffer overflow comes into existence because of too many function calls!

Khushi said:   1 decade ago
No its not the case.

It will take input but the values that will get stored will be unexpected and it may lead to segmentation fault as well.


Post your comments here:

Your comments will be displayed after verification.