Cannot get the correct input in C programming - c

I am writing a simple C program to accept an input number from user and display it just because earlier i was writing some C program and this stupid error is bugging me it wasn't there before until yesterday
#include<stdio.h>
#include<stdlib.h>
int main(void)
{
int a;
printf("Enter a number");
scanf("%d",&a);
printf("Display number%d",&a);
}
Every time i run a program that accept an input it displays a seemingly random value and not the one I entered not just in this program in any other too, here
is the O/p:
Enter a number: 12
Display number : 2752300
Process returned 7(0X7) execution time : 1.880s
Press any key to continue
I don't know whether is the Compiler error or some memory error that is causing this problem but for the record i have tried using different IDE like DEV C/C++, Turbo C/C++ and Code Blocks but the error remains to be same in all of it except in Turbo C/C++ it display a signed number of i enter for eg : if input is 12 it displays: -12.

The problem is in your print statement. You are printing the address of a, not the value. Use print("%d",a);

The %d format specifier for printf expects an int, not an int *:
printf("%d",a);
It's not attempting to write to a, so it doesn't need its address.
If you compile with the warning level turned up (-Wall -Wextra for gcc), it will tell you this:
format ‘%d’ expects type ‘int’, but argument 2 has type ‘int *’

scanf needs a pointer to the variable if it is going to change the variable itself, so we use the address-of operator to get the pointer.
scanf() received "%d", as a parameter and then knows it needs to read an integer and store it in the next variable in the argument list.
#include<stdio.h>
#include<stdlib.h>
int main(void)
{
int a = 0;
printf("Enter a number: ");
scanf ("%d" ,&a);
printf ("%d \n ",a);
return 0;
}

Related

C Program to Accept n Integers in an Array and Search for a Specific Number

(Motivation) I am trying to construct a program in C that allows me to
(1) Enter a certain amount of numbers in an array
(2) Enter what exactly those numbers are
(3) Enter a search value from that array that makes the C program find what position that search value is in.
Basically, I am trying to do this.
(Attempt) Here is what I tried so far.
#include <stdio.h>
#include <stdlib.h>
//Write a 'C' program to accept n integers in an array and search for a specific number.
int main()
{
int a[10],n,i,key;
printf("Enter how many numbers in an array: ");
scanf("&d",&n);
printf("Accept n numbers in an array: \n");
for(i=0;i<n;i++)
{
scanf("&d",&a[i]);
}
printf("Display Array Elements\n");
for(i=0;i<n;i++)
{
printf("%d",&a[i]);
}
printf("Enter search value: ");
scanf("%d", &key);
for(i=0;i<n;i++)
{
if (a[i]==key)
printf("Number found at position %d", i+1);
else
printf("Element not found!");
}
return 0;
}
When I compile this in CodeBlocks (version 20.03), I am able to enter in how many numbers there are in an array, but then after typing in a number, say 4, CodeBlocks prints out
Accept n numbers in an array: 4
Display Array Elements
Enter search value:
Process returned 0 (0x0) execution time : 22.628 s
Press any key to continue.
(Question) How can I improve this code such that it does what (1), (2), and (3) above says? I also welcome alternate methods. I have been trying to replicate what the YouTube video in the link says, but I have not been able to succeed.
I want to mention I have little to no coding experience, and I am learning C for the first time. I also tried searching for similar questions, but given my novice skills in coding, I am not able to take advantage of them. Thank you in advance.
At least these problems:
Code not compiled with a well enabled compiler
Use a compiler with all warnings enabled. This rapidly points out many of code's troubles.
warning: too many arguments for format [-Wformat-extra-args]
scanf("&d", &n);
^~~~
warning: too many arguments for format [-Wformat-extra-args]
scanf("&d", &a[i]);
^~~~
warning: format '%d' expects argument of type 'int', but argument 2 has type 'int *' [-Wformat=]
printf("%d", &a[i]);
Code attempts to print the address and not the value
Printing with "%d" and an address and not an int leads to undefined behavior (UB). Drop the &.
// printf("%d",&a[i]);
printf("%d", a[i]);
Use % #Eric Postpischil
Since &d is not a specifier, "&d" directs scanf() to scan in the characters '&' and 'd' and then move on. If there or not, code simply moved on and used an uninitialized n for the rest of code. In OP's case, n appears to be 0 and so code ended promptly.
// scanf("&d",&a[i]);
scanf("%d", &a[i]);
// ^
Test inputs
Check scanf() return value. #Shawn
Test range
// scanf("&d",&n);
if (scanf("%d", &n) != 1 || n < 1 || n > 10) {
fprintf(stderr, "Invalid numeric input or out of range 1-10\n");
return EXT_FAILULRE;
}

MacOS programming C delivers error: zsh: segmentation fault

As described in the heading, the terminal delivers the error: zsh: segmentation fault. Here is the - pretty basic - code:
#include<stdio.h>
int main(){
int age = 0;
printf("Input your age!");
scanf("%d", &age);
printf(age);
}
thanks for the help solving this problem :)
printf(age);
should be printf("%d", age);
You need to pass in a string literal (eg: "hello world") with a format specifier (exactly the same way you did it in scanf) and then pass the age (not its address as you did with scanf, so without the &) as a second argument.
for example
printf("I am %d years old\n", age);
For the above example, I printed a message that writes "I am [age] years old" and then continues down to a new line (that's the '\n'). The '%d' is a format specifier; what it does is it specifies that in its position, the function should print a value of a specific type (%d specifies an integer). You can have multiple of these specifiers and it prints the arguments you give it in linear order. I would highly recommend you look at this[1], it should explain it better than I can.

Character type gives an int — what is this int?

In a C program, I want to take an int type input but after I run the program, I will give a character type as input but it doesn't get any error and it shows an integer. Why?
Code:
#include <stdio.h>
int main(){
int x;
printf("input: ");
scanf("%d", &x);
printf("the output is %d",x);
return 0;
}
After compilation:
input: a
the output is -1225407932
[Program finished]
You do get an error but you ignored it.
When you type a but scanf() is told to expect an integer, it returns 0 indicating that it failed to convert any input into a number (but that there was data to process; it did not encounter EOF). The character you typed is still in the input buffer, waiting to be processed by a subsequent I/O operation.
The variable x that you passed to scanf() is still uninitialized after the call — it was not modified by scanf() because the conversion failed. Technically, printing an uninitialized variable such as x invokes undefined behaviour, but in practice, you get some quasi-random value output.
If you have initialized the variable you would have got the output as 0. It doesn't give an error because char is just a 8-bit integer which can fit int on into.

Formatted string in scanf() in C

Just like printf(), I was trying to use optional specifiers in scanf() format string. I tried to use the width and precision specifier. Now in printf() it simply reserves the columns and print according to these specifiers but what happens with scanf()? Like what is meaning of %3d and %3.3f here? Is this even relevant in case of scanf()? I have a little idea that width in this case represents the number of characters that are to be read for some particular format but not sure. Below code explains this further:
#include<stdio.h>
int main()
{
int a;
float b;
printf("Enter Numbers:\n");
scanf("%3d %3.3f",&a,&b);
printf("Entered Numbers are\n");
printf("%d %f",a,b);
return 0;
}
Since you specified in the comments that what you really want to know is 'what if i forcefully try to do it' ... Here are the results (with Clang)
warning: invalid conversion specifier '.'
and
warning: data argument not used by format string
The program compiles , however, since these are just warnings.
Upon executing the binary, and entering the variables asked for:
The "%d" for a gets stored properly.
Regardless of what value is entered, the " %3.3f " for b always stores 0.000000
In short, the it does what almost any other code that compiles with warnings does - not behave as intended. This is neither undefined, nor unspecified behaviour, but it is wrong.
Suggestion : Refrain from asking questions that are of the nature ' what happens if I try to compile this '. Just try and see for yourself !

Why my computer crashes when I execute this code in c?

I was practicing about structs in C, so I've tried to execute 2 times this code and twice the computer crashes. I've had turn off the computer twice since my computer crashes.
Compiler is GCC (About MinGW on windows platform). The code is following :
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct person {
char name[50];
int age;
int document;
};
int main(void){
struct person p1;
printf("Data of the first person\n\n");
printf("age: ");
fflush (stdin);
scanf("%i",p1.age );
printf("Document: ");
fflush(stdin);
scanf("%i",p1.document);
printf("Age is: %i and document is: %i ",p1.age,p1.document);
return 0;
}
Sincerely,
NIN.
UPDATE....
Bad news. Now Avast says I`ve created a virus. Therefore Avast delete my exe:
Should I report as false positive or not ?
scanf("%i",p1.age );
When you call scanf, p1.age is an integer with no particular value. So you are asking scanf to store the value you input in no particular place. It's not surprising this causes a crash. You want:
scanf("%i", &p1.age );
This tells scanf to read in an integer and store it at the address of p1.age.
It's surprising your compiler didn't give you a warning. Are you sure you have all of its warnings enabled?
When I try to compile this, I get appropriate warnings:
warning: format ‘%i’ expects argument of type ‘int *’, but argument 2 has type ‘int’ [-Wformat=]
Update: Your anti-virus has heuristics that block software that has suspicious behavior. Your code has bugs, and your anti-virus doesn't know that they're just mistakes and not attempts to do something nefarious. It sounds like you don't have a very good environment set up for experimentation. Let me guess -- you're doing all this from a Windows administrator account.

Resources