I've been teaching myself C during the school holidays and recently tried to write a simple calculator program, which should take in two integers and perform one of four operations to them (+-*/), but whenever the first variable is assigned I get a segmentation fault / core dumped error message. I know this is to do with memory allocation and I have tried using pointers and malloc, though I suspect I am doing so incorrectly.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int calculate(int numberOne, int numberTwo, int operator);
int main(){
//Declaring Variables
int numberOne, numberTwo, total, operator;
int *one, *two, *tot, *op;
//Assigning Variables
printf("Integer 1: ");
scanf("%d", numberOne);
printf("\nOperator 1[+] 2[-] 3[*] 4[/] : ");
scanf("%d", operator);
printf("Integer 2: ");
scanf("\n%d", numberTwo);
//Output Calculatoin Through Function
printf("Calculation Complete: %d is the answer", calculate(numberOne, numberTwo, operator));
}
int calculate(int numberOne, int numberTwo, int operator) {
int total = 0;
do{
switch(operator){
case 1:
total = numberOne + numberTwo;
break;
case 2:
total = numberOne - numberTwo;
break;
case 3:
total = numberOne*numberTwo;
break;
case 4:
total = numberOne/numberTwo;
break;
default:
printf("Error, Invalid Operator, Please Enter A New One: ");
scanf("%d", operator);
}
}while(total ==0);
return total;
}
You need to change
scanf("%d", numberOne);
to
scanf("%d", &numberOne); //%d expects a pointer to int argument
and likewise.
scanf("%d", numberOne);
^ %d expects int * not int
So pass address of int variable in all the scanf statements.
Related
I think this is a really stupid question. I just started with C and made this little "calculator":
#include <stdio.h>
#include <stdlib.h>
int main() {
while(1) {
int a;
int b;
char op;
printf("Enter the first number: ");
scanf("%d", &a);
printf("Enter the second number: ");
scanf("%d", &b);
printf("Enter the operator: ");
scanf("%s", &op);
switch(op) {
case '+':
printf("%d + %d = %d", a, b, a + b);
break;
case '-':
printf("%d - %d = %d", a, b, a - b);
break;
case '*':
printf("%d * %d = %d", a, b, a * b);
break;
case '/':
printf("%d / %d = %d", a, b, a / b);
}
printf("\n");
char cont;
printf("Do you want to continue? (y/n): ");
scanf("%s", &cont);
if(cont == 'n') {
break;
}
}
return 0;
}
But when I run it and try to put in "1" and "1" it puts out the wrong number:
Enter the first number: 1
Enter the second number: 1
Enter the operator: +
1 + 0 = 1
Do you want to continue? (y/n): n
This is probably some dumb problem but I don't get it xD
You're reading the operator as a string, yet 'op' is a single char.
As a result, the terminating '\0' is written to the next byte in memory, which in this case is the first byte of the variable 'b' ('b' and 'op' are both on the stack).
As a fix I would suggest:
make 'op' a char array of size 2
use fgets to ensure that only 1 byte is read
char op[2] = {0};
fgets(op,2,stdin);
I am a beginner in C programming.
I was writing a simple program to calculate average.
Here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
int main()
{
int n, s = 0, num, i;
float avg;
printf("Enter value of total no\n");
scanf("%d", &n);
for (i=1; i<=n; i++)
{
void pri(int i){
switch(i){
case 1:
printf("st");
break;
case 2:
printf("nd");
break;
case 3:
printf("rd");
break;
default:
printf("th");
break;
}
}
printf("Enter %d pri(i) number\n", i);
scanf("%d", &num);
s += num;
}
avg = s / n;
printf("The average is %f",avg);
return 0;
}
But pri(i) is not working as I expected. But later I found another way to do this, so here is the second version of this code:
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
int main()
{
int n, s = 0, num, i;
float avg;
printf("Enter value of total no\n");
scanf("%d",&n);
for (i=1; i<=n; i++)
{
void pri(int i){
switch(i){
case 1:
printf("enter 1st number\n");
break;
case 2:
printf("enter 2nd number\n");
break;
case 3:
printf("enter 3rd number\n");
break;
default:
printf("enter %dth number\n",i);
break;
}
}
pri(i);
scanf("%d", &num);
s += num;
}
avg = s / n;
printf("the average is %f",avg);
return 0;
}
I want to get the results of this second piece of code from the first version.
Can I call functions in printf which are defined somewhere in program?
You cannot tell printf() to call another function in the middle of its execution. printf() expects to receive a formatting string and arguments to replace parts of this string. What you're trying to do (embed a function call in the formatting string) is not possible for a number of reasons.
What you can do is return the string instead of printing it and use it as argument.
const char *pri(int i) {
switch(i) {
case 1:
return "st";
case 2:
return "nd";
case 3:
return "rd";
default:
return "th";
}
}
printf("enter %d%s number\n", i, pri(i));
C doesn't support nested functions (function defined inside another function). Your code works because your compiler adds support for such functions as an extension. In general, you should probably avoid nesting functions.
What seems to be the problem in my code? I wish to make a program that makes allows the user to choose from a list of choices/menu. The user chooses one and a function runs. After the function executes the menu appears again until the user decides to quit.
My code is as follows:
#include <stdio.h>
#include <stdlib.h>
int evaluate(int num);
int binaryPrinter(int dec);
int hexaPrinter(int dec);
int militaryTime(int hh, int mm);
int main(void)
{
int choice, x, y;
do {
printf("Type the number of your choice:\n1: Place value evaluation\n2: Convert a Decimal to Binary\n3: Convert a Decimal to Hexadecimal\n4: Convert Standard time to Military time\nEnter Number of Choice: ");
scanf("%d, &choice");
(void) getchar();
switch (choice){
case 1:
printf("Enter number to be evaluated:");
scanf("%d, &x");
int evaluate(int x);
break;
case 2:
printf("Enter a decimal number: ");
scanf("%d, &x");
int binaryPrinter(int x);
break;
case 3:
printf("Enter a decimal number: ");
scanf("&d, &x");
int hexaPrinter(int x);
break;
case 4:
printf("Enter time in standard format: ");
scanf("%d:%d, &x, &y");
int militaryTime(int x, int y);
break;
default:
printf("Invalid choice. Please choose only among the choices.");
}
}while(choice != 5);
return 0;
}
This is what is displayed after inputing the number of choice: Process returned -1073741819 <0xC0000005>
-EDIT-
I have recognized the mistake I have made. But the result's still the same.
here's my new code, but same error: Process returned -1073741819 <0xC0000005>
#include <stdio.h>
#include <stdlib.h>
int evaluate(int num);
int binaryPrinter(int dec);
int hexaPrinter(int dec);
int militaryTime(int hh, int mm);
int main(void)
{
int choice, x, y;
do {
printf("Type the number of your choice:\n1: Place value evaluation\n2: Convert a Decimal to Binary\n3: Convert a Decimal to Hexadecimal\n4: Convert Standard time to Military time\nEnter Number of Choice: ");
scanf("%d", &choice);
(void) getchar();
switch (choice){
case 1:
printf("Enter number to be evaluated:");
scanf("%d", &x);
evaluate(x);
break;
case 2:
printf("Enter a decimal number: ");
scanf("%d", &x);
binaryPrinter(x);
break;
case 3:
printf("Enter a decimal number: ");
scanf("%d", &x);
hexaPrinter(x);
break;
case 4:
printf("Enter time in standard format: ");
scanf("%d:%d", &x, &y);
militaryTime(x, y);
default:
printf("Invalid choice. Please choose only among the choices.");
}
}while(choice != 5);
return 0;
}
Try this code
#include <stdio.h>
#include <stdlib.h>
int evaluate(int num);
int binaryPrinter(int dec);
int hexaPrinter(int dec);
int militaryTime(int hh, int mm);
int main(void)
{
int choice, x, y;
do
{
printf("Type the number of your choice:\n1: Place value evaluation\n2: Convert a Decimal to Binary\n3: Convert a Decimal to Hexadecimal\n4: Convert Standard time to Military time\nEnter Number of Choice: ");
scanf("%d", &choice);
(void) getchar();
switch (choice){
case 1:
printf("Enter number to be evaluated:");
scanf("%d", &x);
evaluate(x);
break;
case 2:
printf("Enter a decimal number: ");
scanf("%d", &x);
binaryPrinter(x);
break;
case 3:
printf("Enter a decimal number: ");
scanf("&d", &x);
hexaPrinter( x);
break;
case 4:
printf("Enter time in standard format: ");
scanf("%d:%d", &x, &y);
militaryTime( x, y);
break;
default:
printf("Invalid choice. Please choose only among the choices.");
}
}while(choice != 5);
return 0;
}
You have used wrong syntax of the scanaf()
it's not like scanf("%d,&choice");
it is like scanf("%d",&choice);
And also missed the syntax of function call
it's not like int evaluate(int x); it is like evaluate(x)
Your scanf statements are all wrong. It usually takes to parameters. A format string containing format specifiers to determine what kind of value and how many values to read and a pointer to the variable were to store the read value (multiple pointers in case of multiple specifiers).
// What you got so far
scanf("%d, &choice"); // <-- format string and pointer to variables are combined
// How it should look like
scanf("%d", &choice); // format string "%d" containing 1 format specifier to read an int
// and a pointer to the variable choice to store the read value
Ok now to the next mistake. When declaring a function you need to write down the whole function header (returnType functionName(ParameterType1 Parameter1, ParameterType2 Parameter2, ...)) however when you want to call that funtion all it needs is its name and the parameters BUT whithout theire type.
So declaring a function like this int evaluate(int num) like you did at the very beginning of your code is fine but when calling it in your switch all it needs is the name (evaluate) and the values, or variables you want to pass to the function as parameters (evaluate(x)).
So now all together:
printf("Type the number of your choice:\n1: Place value evaluation\n2: Convert a Decimal to Binary\n3: Convert a Decimal to Hexadecimal\n4: Convert Standard time to Military time\nEnter Number of Choice: ");
scanf("%d", &choice); // scan an integer value and store it in choice
switch (choice)
{
case 1:
printf("Enter number to be evaluated:");
scanf("%d", &x);
evaluate(x);
break;
case 2:
...
}
I am pretty new in C and I came across this problem and didn't understand why does this happen. After I run the following code there's an error message which says:
"Run-Time Check Failure #2 - Stack around the variable 'op' was corrupted".
FYI, the program should ask the user for 2 integers and a mathtematical operator, and then it performs the operation on the two numbers (e.g 5,3,+ --> 5+3=8). It works just fine, except the error message that pops in the end.
I'm only interested in understanding why this message pops, there is no need to give me notes about my coding style etc. - it is all still new to me...
Thanks
#include <stdio.h>
#include <stdlib.h>
void askUser();
double calculateImpl(int *, char *);
typedef struct _myStruct
{
double result;
double(*calculate) (int *, char *);
} myStruct;
int main(void) {
puts("Hello World!");
askUser();
return EXIT_SUCCESS;
}
void askUser(){
int numbers[2] = { 0, 0 };
char op[1] = { '.' };
printf("Please choose 2 integers:\n");
printf("1st integer: ");
scanf("%d", &numbers[0]);
printf("\n2nd integer: ");
scanf("%d", &numbers[1]);
printf("\nchoose a mathematical operator\n(+,-,*,/; can't choose / if the second number is 0: ");
scanf("%s", &op[0]);
while (numbers[1] == 0 && op[0] == '/'){
printf("\ncan't choose / while the second number is 0.\nchoose a different operation: ");
scanf("%s", &op[0]);
}
printf("the result of %d %s %d is ", numbers[0], &op[0], numbers[1]);
myStruct strct;
strct.calculate = calculateImpl;
strct.result = strct.calculate(numbers, op);
printf("%lf\n", strct.result);
}
double calculateImpl(int * numbers, char * op){
double result = 0;
switch (op[0])
{
case '+':
result = numbers[0] + numbers[1];
break;
case '-':
result = numbers[0] - numbers[1];
break;
case '*':
result = numbers[0] * numbers[1];
break;
case '/':
result = numbers[0] / numbers[1];
break;
default:
break;
}
return result;
}
scanf("%s", &op[0]);
^ use %c
Use %c specifier to take input in character variable . You pass wring argument to %s specifier.
Also there is scanf in while loop , use correct specifier there also .
Declare op as char -
char op; // you don't need char op[1]
Wrtie like this -
scanf(" %c", &op); // at both places
And inside after loop this line -
printf("the result of %d %s %d is ", numbers[0], &op[0], numbers[1]);
To print char don't pass its address and use %c -
printf("the result of %d %c %d is ", numbers[0], op, numbers[1]);
Also then pass your function char not char * -
double calculateImpl(int *, char );
and make changes accordingly in your program.
Why do I keep getting this error? HELP ME this is homeowrk. I'm obiously new to programming help.
$ gcc homework.c
homework.c: In function ‘main’:
homework.c:32:6: error: static declaration of ‘DisplayMenu’ follows non-static declaration
homework.c:11:7: note: previous declaration of ‘DisplayMenu’ was here
#include <stdio.h>
void DisplayMenu();
void numberPlus10();
void numberTimes2();
void numberMinus1();
void numberTimesnumber();
int main (void)
{
int choice;
void DisplayMenu();
scanf("%i", &choice);
switch (choice)
{
case 1:
numberPlus10();
break;
case 2:
numberTimes2();
break;
case 3:
numberMinus1();
break;
case 4:
numberTimesnumber();
break;
default:
break;
}
void DisplayMenu()
{
printf("1. Number + 10\n");
printf("2. Number * 2\n");
printf("3. Number - 1\n");
printf("4. Number * Number\n");
}
void numberPlus10()
{
int x;
printf("Please enter a number:\n");
scanf("%i", &x);
printf("Your number + 10 is %i\n", x + 10);
}
void numberTimes2()
{
int x;
printf("Please enter a number:\n");
scanf("%i", &x);
printf("Your number * 2 is %i\n", x * 2);
}
void numberMinus1()
{
int x;
printf("Please enter a number:\n");
scanf("%i", &x);
printf("Your number - 1 is %i\n", x - 1);
}
void numberTimesnumber()
{
int x;
printf("Please enter a number:\n");
scanf("%i", &x);
printf("Your number squared is %i\n", x * x);
}
}
Pengyu CHEN is ofcourse right! But! You have another error there.
int choice;
void DisplayMenu(); // You should not declare a function here.
scanf("%i", &choice);
I guess you intend to call this function - so just remove "void" from the beginning of the line.
int choice;
DisplayMenu(); // Call DisplayMenu
scanf("%i", &choice);
And ... please read language specs
In C we don't implement functions inside any blocks. Instead functions shall be implemented in global scope.
Remove the very last right bracket and put it right after end of the switch in int main(void), and there shall be no more errors.
EDITED:
First of all.. I'm sure above is why your source code fails to compile.
Also, please check David's answer, since we all believe that you made a function declaration while you're intending to call it -- although this mistake didn't trigger an compile time error.