Hi I just started C as my first programming language.
I was playing around a bit with scanf() and found something strange.
#include <stdio.h>
#include <Windows.h>
int main()
{
int x;
printf( " Type any number : " );
scanf( "%d", &x );
printf( "You entered %d.\n", &x );
system("pause");
return 0;
}
It always shows me a result of 7 or 8 digit number.
How is it possible?
You printf x's address instead of value. Fix like this:
printf("You entered %d.\n", x);
scanf wants the address where to store the result, printf can take the value itself.
You are printing out the address of x. Remove the '&' before it in the printf and you should see the right thing.
Putting an & before a variable gets a pointer to it - this is necessary in the scanf because it must change the value, but since printf only uses the value, no pointer is needed (except for strings, which are always pointers).
Related
I am an absolute beginner in C, and I wrote this code in codeblocks and built it, it had no errors. The program is, we input two integers and display, sum, subtraction, multiplication, and division of no1 and no2.
Here's the code :
#include <stdio.h>
int main ()
{
int no1,no2,sum,sub,multi,div;
printf("Enter your first number");
scanf("%d", &no1);
printf("Enter second number");
scanf("%d", no2);
sum=(no1+no2);
sub=(no1-no2);
multi=(no1*no2);
div= (no1/no2);
printf ("%d + %d = %d \n",no1,no2,sum);
printf ("%d - %d = %d \n",no1,no2,sub);
printf ("%d * %d = %d \n",no1,no2,multi);
printf ("%d / %d = %d \n",no1,no2,div);
return 0 ;
}
I got 0 errors but when I ran it, cmd opens, and then I input values for no1 and no2 then the program crashes and gives the message windows will look into the issue.
Look closely at the this snippet: scanf("%d", no2);
Say you declare a variable named foo.
int foo;
This variable occupies some memory. It occupies four bytes of memory (because an int is four bytes wide).
Now let's declare another variable.
int *foo_ptr = &foo;
foo_ptr is declared as a pointer to int. We have initialized it to point to the foo variable.
As I said, foo occupies some memory. Its location in memory is called its address. The char '&' is the “address-of" operator.
This operator returns the address of an variable. In our case foo, thus foo_ptr now point to the address memory of the foo variable.
Think of every variable as a box. foo is a box that is sizeof(int) bytes in size. The location of this box is its address. When you access the address, you actually access the contents of the box it points to.
You missed '&' here...
printf("Enter second number");
scanf("%d", &no2);
You forgot to put '&' at the second scanf :)
I was teaching the C programming language to a friend and we came up with something I could not explain. This is the code we wrote:
#include <stdio.h>
int main(void)
{
char num1;
char num2;
printf("%s", "Enter the first number: ");
scanf("%d", &num1);
printf("%s%d\n", "The number entered is:", num1);
printf("%s", "Enter the second number: ");
scanf("%d", &num2);
printf("%s%d\n", "The number entered is:", num2);
printf("%s%d\n", "The first number entered was:", num1); /* This was done for testing */
printf("%s%d\n", "The sum is:", num1+num2);
return 0;
}
The weird thing is that we tried to do 5 + 6 and we expected to get 11 but instead got 6, I added a line to see what's going on with the first number and it becomes 0 after the second number is read.
I am aware that the variables should be an int (in fact the original code was like that and worked) but my understanding is that a char is a small integer so I thought it would be 'safe' to use if we were adding small numbers.
The code was tested and compiled on a Linux machine with cc and on a Windows machine with cl. The output was the same. On the Windows machine the program throw an error after the addition.
I would like an explanation on why this code is not working as I expected. Thanks beforehand.
You cannot pass a pointer to a different datatype to scanf. scanf will write to memory assuming you gave it a pointer to what it expected (e.g. int for %d), and will exhibit wonderful undefined behaviour if you give it a pointer to a different datatype.
Here, what is most likely happening is that scanf is overwriting e.g. 4 bytes on your stack when your chars only take up 1 byte, so scanf will just be happily writing right over some other variable on your stack.
a char is a small integer so I thought it would be 'safe' to use it if we were adding small numbers.
That is correct, char is a small integral type , and it's OK to use it in integer arithmetic(although char may be signed or unsigned which may causes the result unexpected).
But the problem is, a pointer to char can NOT be used in a place where a pointer to int is expected. And this is the case for scanf("%d", &num1);, the second parameter is expected to a of type int *.
I'm trying to create a program that lets the user enter numbers(maximum entries>10^6) until a negative is encountered. I've tried a lot of version but they either don't register that a negative value is entered or they crash.
This is where I'm currently at:
#include <stdio.h>
#define HIGHEST 999999
int main(){
int i=0, entry, sum=0;
while(i<HIGHEST){
scanf("%i", entry);
if(entry>0){
sum+=entry;
}
else{
i=HIGHEST;
}
i++;
}
printf("Sum: %i", sum);
system("pause");
}
Your problem is on this line:
scanf("%i", entry);
Which should be:
scanf("%i", &entry);
You need to pass in the address of the integer variable that will store the scanned value. Since
entry was never initialized, it is just filled with garbage/whatever is in memory and not the entered value. See this reference, which states,
"Depending on the format string, the function may expect a sequence of additional arguments,
each containing a pointer to allocated storage where the interpretation of the extracted
characters is stored with the appropriate type"
You provide a way to leave if the entered number is too big:
while(i<HIGHEST){
But nothing to leave if it is less than 0; Try this:
while((i<HIGHEST)&&(i>=0)){
Additionally, #OldProgrammer is correct, your scanf() should be as he has pointed out.
My C program is giving the number "32767" when I enter a letter, but when I enter an integer it tells me the number that I entered.
why will my program not tell me what letters I entered? why is it giving me the number "32767"?
#include <stdio.h>
main()
{
int number;
printf("Enter an integer\n");
scanf("%d",&number);
printf("Integer entered by you is %d\n", number);
return 0;
}
If scanf doesn't find what it's looking for (in this case, an int), it will simply return without modifying whatever gets passed in. In other words, scanf won't change number, so it'll have it's old value, which, in this case, is undefined (since it's not initialized).
What you are seeing is "undefined behaviour", which pretty much means "anything can happen". The value in number, in particular, can have any value, because it has not been initialized. If you initialize it int number = 42; it will (probably) print 42, but I'm not sure that's guaranteed.
If you want printf() to display characters and scanf() to get that data, you must point that it's a character, using "char" instead of "int" and use "%c" instead of "%d".
Something like this (I still used the "number" variable and the description in the printf() about the " integer":
#include <stdio.h>
main()
{
char number;
printf("Enter an integer\n");
scanf("%c",&number);
printf("Integer entered by you is %c\n", number);
return 0;
}
I just started my C language and I came to this error. I tried to look up online but other threads contain ARRAY which I am not familiarize with.
#include<stdio.h>
int main(void){
char input;
printf("ASCII testing\n");
scanf( "%d", &input); //the error occurs here but would like to know the solution
printf("answer is : %c\n" , input);
system("pause");
return 0;
}
"Run-Time Check Failure #2 - Stack around the variable 'input' was corrupted."
Simple point-out will be much appreciated
//Edited
Well I would like to enter value "66" so that the outcome would be B. The scanf("%c , &input) accepts 1 keystroke from the keyboard so that's not what I am looking for. But nevertheless, thank you for the replies
The Problem
%d is the format specifier for integer input, leading the compiler to assume that &input points to an integer rather than a character.
scanf( "%d", &input);
should be
scanf( "%c", &input);
Why this corrupts the stack
The reason for the corrupted stack is that input is allocated on the stack, and scanf assumes it occupies 4 bytes (on a 32 bit platform) rather than the 1 byte actually allocated on the stack. As a result, other things on the stack (other variables, return address, ...) are overwritten.
The %d format specifier in scanf() requires a pointer to an int variable, not a pointer to a char. Try:
int input;
scanf( "%d", &input);