Can't get integer input in c - c

I seriously don't know what is wrong. It may be something very simple, but I can't find the error. I wrote this very simple program in C:
#include<stdio.h>
int main(void) {
int n;
scanf("%d", &n);
printf("\n%d", &n);
return 0;
}
But when I ran it, this is what I got:
1 // My input
-1936471972
What am I doing wrong?
Thanks in advance!

I'll just post what the others have already pointed out:
int main(void) {
int n;
scanf("%d", &n);
printf("%d\n", n);
^^ ^
return 0;
}
Remove the & from &n if you just want to display the value of the variable (you were basically printing the address of the variable) and move the \n after you have printed the variable as explained by Weather Vane.

I seriously don't know what is wrong.
printf("\n%d", &n); use a print specifier of "%d", which expects an int. &n is the address of an int. What is really good about this is the modern compilers and compilers with their warnings well enable, will automatically warn about this error. This saves you time! No need for an SO post.
Proficient coders uses tools like a compiler with is warnings well enabled to be efficient and focus on the subtle problems a compilers cannot detect. Using printf("\n%d", n); or printf("%d\n", n); may solve today's small problem, but using a better compiler environment is really the thing to learn from all this.

Use that
printf("%d\n", n);
instead of
printf("\n%d", &n);

scanf takes a variable address as a parameter, butprintf takes the variable value. Try changing the line to
printf("\n%d", n);

Related

Why is the following C code asking input twice?

#include<stdio.h>
int main()
{
int i, j;
for(scanf("%d ",&i); i<=10; i++)
printf("%d ",i);
return 0;
}
I am a beginner in the programming world so please help me understand why on compiling the above C code it asks inputs twice.Maybe there's some logic to loop here I might be missing. Please help me understand.Thanks in advance.:)
Change this:
scanf("%d ",&i);
to this:
scanf("%d",&i);
Read more in What does space in scanf mean?
Currencly, you placed scanf() in a for loop, which it asks for input for a 10 times.This will not happen when you remove scanf() from for loop.
I was facing the same problem and the only change I did was to change "%d " to "%d". This solves the problem.

In Visual Studio 2013, "Run-Time Check Failure #2 - Stack around the variable 'b' was corrupted."

I would first like to thank you for looking into my question.
I have been coding using Code Blocks ever since I started coding with C, and recently I had to switch to using Visual Studio for my college lab assignments. We had a pretty easy assignment this week, but I seem to keep running into this error that ONLY pops up when using Visual Studio, and not in any other IDEs. I was wondering if someone could help me resolve this issue, and tell me what I am doing wrong? I will attach my code below.
Thank you so much!
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
#include<time.h>
void main()
{
srand(time(NULL));
int a, n;
char b ='y';
while (b == 'y')
{
n = rand() % 3000 + 1; // 1-3000
puts("I have generated a number between 1 and 3000. Can you guess mynumber?\nPlease type your first guess (0-3000):");
scanf("%d", &a);
while (a != n)
{
if (a > n)
printf("Too high. Please try again.\n");
if (a < n)
printf("Too low. Please try again.\n");
scanf("%d", &a);
}
printf("Excellent! You guessed the number!\n");
printf("Would you like to play again? (y or n)\n");
scanf("%s", &b);
}
printf("Have a nice day.\n");
system("PAUSE");
}
This code is designed to generate a random(ish) number from 1-3000, and have the user guess it. The user then has the option to choose to play again or not. The error occurs when the user types 'n' to end the outer while loop.
Thanks again!
Heed the dangers of scanf:
scanf("%s", &b);
b is a char, yet you gave scanf the specifier of %s. The %s specifier is for character buffers, not single chars. What is happening is that scanf assumes that b is a pointer to a buffer, and thus you get a memory overwrite.
You should specify %c as this is the specifier for a single char.
Also, just because you didn't see this in Codeblocks (probably using gcc) doesn't mean the program was ok, and it is only Visual Studio has a problem. The program was wrong, and what you observed is undefined behavior. When you overwrite memory, anything can happen, including "working ok".

Why am I getting a segmentation fault error with the following code?

I'm a Python programmer studying C. I receive a segmentation fault on the final printf() of the following code. I'm sure it has something to do with the expression but I'm not sure what the problem is. Unfortunately, the expression works in Python so I'm unable to get a more specific error message. I'm using the GCC compiler in Debian.
#include <stdio.h>
int main(void)
{
int n;
printf("Enter a two-digit number: ");
scanf("%d",n);
printf("The reversal is: %d\n", (n % 10) * 10 + (n / 10));
return 0;
}
Pass address of n to scanf() as
scanf("%d", &n);
try scanf("%d",&n);
it has no way to put anything into n unless it has a pointer to n
You need to provide a pointer to an int as the argument to scanf, not the int itself; &n rather than just n.

does arrays and input with scanf goes hand in hand?

What is wrong with the following code written in c language?
I encountered a segmentation fault. what is it?
int a[2];
for(i=0;i<2;i++)
{
scanf("%d",a[i]);
printf("%d",a[i]);
}
Why couldn't it run? leave about declarations. Does scanf have any delay problems?
This:
scanf("%d",a[i]);
is wrong. The %d format specifier requires a pointer to where the value should be stored after conversion, i.e. it should be:
scanf("%d", &a[i]);
This is required since otherwise you pass the value of a[i] to scanf(), giving it no way to change the value. By passing the address of the value, scanf() can simply write to the provided memory address to change the value that is stored there. With printf(), you don't want your values to be changing, so passing them directly to printf() is fine.
Also, conversions (like many other forms of I/O) can fail, so you should check the return value before relying on the conversion having succeeded:
if( scanf("%d", &a[i]) == 1 )
printf("%d\n", a[i]);
You should probably read the manual page for scanf() a couple more times. :)
Pass the address of a[i] to scanf instead of the value of a[i].
scanf("%d",&a[i]);

Why is %hd necessary in scanf?

I created a very simple progam whith a menu,
that take a value, then memorize it into the
local variable value, and finally with the
second option the progam prints the value.
my question is:
Why does the program work only if I add an "h"
to the scanf parameter?
In other words: what kind of relation there is
between scanf() and my local int value variable?
thanks!
p.S. (I used Dev-C++ (GCC) to compile it.
With Visual Studio it works)
#include <stdio.h>
main () {
int value = 0;
short choice = 0;
do {
printf("\nYour Choice ---> ");
scanf("%d", &choice); /* replace with "%hd" and it works */
switch (choice) {
case 1:
printf("\nEnter a volue to store ");
scanf("%d", &value);
getchar();
printf("\nValue: %d", value);
break;
case 2:
printf("\nValue: %d", value);
break;
}
} while (choice < 3);
getchar();
}
With scanf, the "h" modifier indicates that it's reading a short integer, which your variable choice just happens to be. So the "%hd" is necessary to write only two bytes (on most machines) instead of the 4 bytes that "%d" writes.
For more info, see this reference page on scanf
The variable choice is of type short so that's why you need the %h specifier in scanf to read into it (in fact you don't need the d here). The int type just requires %d. See the notes on conversions here
You're reading into a short. The h is necessary because %d is the size of an int by default. See this reference page on scanf.
It looks like your problem is that choice is a short, which is (generally) 2 bytes long, while %d expects an integer, which is (generally) 4 bytes long… So the scanf clobbers whatever comes after choice on the stack.
choice is a short and %d specifies an int.
When you specify %d, scanf has to assume that the associated argument is a pointer to an int sized block of memory, and will write an int to it. When that happens it will likely be writing to data adjacent to but not part of choice and the results are undefined and probably not good! If it works in one compiler and not another that is simply the nature of undefined behaviour!
In GCC -Wformat should give you a warning when you make this error.
From the comp.lang.c FAQ:
Why doesn't the code short int s; scanf("%d", &s); work?
Someone told me it was wrong to use %lf with printf. How can printf use %f for type double, if scanf requires %lf?
%d is for reading an int, not a short. Your code never really "worked" -- it just appears that in this case you didn't notice any difference between what you wanted and the undefined behavior you got.
The modifier for scanf to input a variable of type short is %hd. Hence you need to specify the correct modifier.
scanf("%d",&integer); // For integer type
scanf("%hd",&short_int); // For short type
Hence it doesnt work.
Depending upon numeric padding, endian-ness, and other such issues, you may be storing either the upper or lower part of the input value into choice; you are storing the rest of the input value into memory that may or may not be being used for anything else.

Resources