This is probably a very elementary problem, but I cannot find the answer anywhere, and this is the first time I've had the problem after several weeks of programming in C. In essence, if I write some code looking something like this:
int size;
scanf("%d", &size);
printf("size is %d", &size);
If I input, say, size = 2, the program will print back out something along the lines of 133692 or a similar number. Why is this? What have I done wrong here?
Try
printf("size is %d", size);
& gives you the memory location (address) of a variable.
printf("size is %d", &size);
So, the above will print the memory location(address) of size, not the value stored in size.
You have to do:
printf("size is %d", size);
instead. This prints the value of the int object size.
But
printf("size is %d", &size);
is undefined behavior.
You are printing the address of size, i.e., &size.
Just pass a plain size.
Remove the & in the printf statement as &size --> prints the address.
printf("size is %d", size);
The calling conventions are different in printf, and scanf.
Printf's arguments are typically by value (no &), but scanf has to have pointers. (&)
(You can't put a new value to e.g. 1.0, but you can print it...)
Related
I apologies in advance if there is a stupid error in this code, but I can't seem to trouble shoot it. My problem is this, I compile with GCC-8 (installed on Mac via home-brew), then execute in the terminal. When using int do define variables s & a, I get zeros as output using the print statements below. If I declare s & a variables as double I still get zeros for the first two print statements, and 1024 for the last print statement. I'm just lost as to what is going on. Appreciate any help!
/* square code */
#include <stdio.h>
int main() {
int s, a;
printf("enter the length of your square \n");
scanf("%f", &s);
a= s * s;
printf("the area of your square is %f cm using f placeholder \n", a);
printf("the area of your square is %lf cm uning fl placeholder\n", a);
printf("the area of your square is %d cm using d placeholder \n", a);
return(0);
}
int s;
scanf("%f", &s);
If s is an int then you need to scan it in like an int using "%d" instead of "%f". What you are doing is undefined behavior, both in scanf() and printf(). An integer needs to be scanned and printed as an integer.
I think the misunderstanding is that you treat the conversion specifiers %d and %f as defining only the output formatting, regardless of the type of value passed.
Actually each conversion specifier is tightly coupled with a particular type of argument it will accept; For example, %d is defined for integral types only, and all other types like floating point or string used together with %d will yield undefined behaviour (cf, for example, cpp-reference of printf for a more detailed explanation).
So double f=1.2;printf("%d",f) will not format a floating point value 1.2 as integral (someone might expect 1 being the output); It rather yields undefined behaviour, having any output (even no output), a crash, a... whatever.
Same applies to scanf-format specifiers, of course.
So if data type is int, use %d; if data type is double, use %f.
In your code you use s as an int, and when you use scanf you are using %f instead of %d. That's the reason why you are getting the first two outputs as a zero.
As for the third output, you will get the expected value, because in that case you are correctly using %d. See the code below:
int s;
printf("enter the value");
scanf("%d", &s);
printf("the area of square is=", s*s);
Hey guys thanks so much for the help. Before checking back this morning I tried one more thing, and alas it was a stupid error.
When declaring "double s,a", I realized my scanf() function was using scanf("%f",s) as opposed to the correct scanf("%lf", s)".
Also thanks for the help for use of %d when using "int s,a".
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 :)
For this code below (in C)
int small_a, small_b;
printf("Please input two numbers\n");
scanf_s("%d %d", &small_a, &small_b);
printf("%d %d", &small_a, &small_b);
int test_2nd = small_a - small_b;
if (test_2nd < 0) {
printf("a is smaller %d", &small_a);
}
else {
printf("b is smaller %d", &small_b);
The values it prints when I write 4 and 2 is a huge six digit number (5504620 and 5504608 in this case) I don't understand where it goes wrong. stdio.h has been included as a header.
The problem here is in the print statement. In the code
printf("%d %d", &small_a, &small_b);
you don't need (want) to take (print) the address. Remove that &.
That said, this actually invokes undefined behavior. %d with printf() expects an argument of type int and you're essentially supplying an int *, causing the UB.
FWIW, to print an address (pointer), you need to use %p format specifier and cast the argument to void *
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);
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 *.