I would like to pass array of structure as a parameter of int function but every time I try to do it. I get the [Error] expected ';', ',' or ')' before '.' token on line 19 where the int function name add is. If I change to int add(int totalCost,struct items *input,int quantity) there will be [Warning] passing argument 2 of 'add' makes pointer from integer without a cast.
#include<stdio.h>
#include<string.h>
struct items
{
int No;
char singleitem[29];
int cost;
};
struct items input[5] = { {0, "Aluminium-air battery",355}, { 1, "Bunsen cell",500}, { 2, "Dry cell",550 }, { 3,"Galvanic cell",350},
};
struct items* ptr = input;
int main()
{
int nonRechargeableBatteries,i=0,choice,c=1,a[10],totalCost=0,quantity=0;
int add(int totalCost,struct items input[i].cost,int quantity)
{
totalCost+=input[i].cost*quantity;
return totalCost;
}
for(i=0; i<5; i++)
a[i]=0;
do
{
//C is 1 by default
if(c==1)
{
printf("\npress number in front of command that you would like to do\n");
printf("1 - non-rechargeable batteries\n2 - cart summary\n");
printf("Enter : ");
scanf("%d",&choice);
switch(choice)
{
case 1:
{
int nonRechargeableBatteries;
printf("\nselect various kind of battery to buy\n1 - Aluminium–air battery\n2 - Bunsen cell\n3 - Dry cell\nAny other number to exit\n");
scanf("%d",&nonRechargeableBatteries);
switch(nonRechargeableBatteries)
{
case 1:
{
int num;
printf("You chose Aluminium–air battery.\nPress 1 to add to the cart.\nAny other number to cancel\n");
scanf("%d",&num);
if(num==1)
{
printf("enter how many items you want : ");
scanf("%d",&quantity);
a[0]+=quantity;
totalCost = add(totalCost,input[0].cost,quantity);
}
break;
}
.
.
.
}
break;
}
case 2:
{
printf("No\tItems%-21sQuantity\tCost\n"," ");
for(i = 0 ; i<5 ; i++,ptr++)
{
if(a[i]!=0)
{
printf("%d\t%s%-4s%d\t\t%d\n",input[i].No,input[i].singleitem," ",a[i],(input[i].cost*a[i]));
}
}
printf("\nTotal Cost\t\t\t\t\t%d\n",totalCost);
printf("continue shopping Enter\n1 to Add Item\n2 to Delete Items\n3 Add or subtract existing item(s) in cart \nAny other number to Exit\n");
scanf("%d",&c);
}
default:
{
if(c==1)
printf("Enter Valid Categories Choice\n");
else;
break;
}
}
if(choice>0&&choice<2)
{
printf("No\tItems%-21sQuantity\tCost\n"," ");
for(i=0; i<5; i++)
{
if(a[i]!=0)
{
printf("%d\t%s%-4s%d\t\t%d\n",input[i].No,input[i].singleitem," ",a[i],(input[i].cost*a[i]));
}
}
printf("\nTotal Cost\t\t\t\t\t%d\n",totalCost);
printf("continue shopping Enter\n1 to Add Item\n2 to Delete Items\n3 Add or subtract existing item(s) in cart \nAny other number to Exit\n");
scanf("%d",&c);
}
else;
}
}
while(c==1 || c==2 ||c==3);
printf("Your total cost is %d\n",totalCost);}
If I change to int add(int totalCost,struct items *input,int quantity) there will be [Warning] passing argument 2 of 'add' makes pointer from integer without a cast.
Of course if you declare the function parameter input to be of type struct items *, you must not pass an int argument input[0].cost, but a struct items * as declared:
totalCost = add(totalCost, input, quantity);
Related
I am trying to make a program where the user inserts the price of a certain item of his choice, then that price is stored in a list, and the user can expand that last as he wishes, but there is a problem, even though I have the exact same arguments and parameters, the array "prices" is considered to be a pointer for some reason.
#include <stdio.h>
void ask(char ques, int index, double prices[index], double price)
{
printf("Do you want to expand your list y/n: ");
scanf("%c", &ques);
printf("What do you want the price of the next item to be: ");
scanf("%lf", &price);
switch (ques)
{
case 'y':
prices[index + 1] = price;
case 'n':
main();
}
}
int main()
{
int index = -1;
double prices[index];
double price;
char ques;
ask(ques, index, prices[index], price);
}
I have this error: argument of type "double" is incompatible with parameter of type "double *"C
A solution using an array on the stack to store the prices.
prices.c
#include <stdio.h>
void ask(double prices[], int *elements, int max_elements)
{
if (*elements >= max_elements) {
printf("List is already full. (%d elements)\n", *elements);
return;
}
while (*elements < max_elements) // as long as there is space left
{
double price;
printf("What do you want the price of the next item to be: ");
scanf("%lf", &price);
prices[*elements] = price; // store price in array
*elements += 1; // increase number of elements
if (*elements == max_elements) {
printf("List is full. (%d elements)\n", max_elements);
break; // leave loop
}
char ques;
printf("Do you want to expand your list (y/n): ");
scanf(" %c", &ques);
if (ques == 'n') {
break; // leave loop
}
}
}
int main()
{
const int MAX_ELEMENTS = 10000; // 10000 prices should be enough for now
double prices[MAX_ELEMENTS]; // array to store 10000 prices
int elements = 0; // number of prices, currently none
ask(prices, &elements, MAX_ELEMENTS); // let user fill it
for (int i = 0; i < elements; i++) {
printf("%3d: %.2lf\n", i + 1, prices[i]); // print price number and price
}
return 0; // return 0 to indicate no error
}
Let's see how it works so far:
$ gcc -Wall prices.c
$ ./a.out
What do you want the price of the next item to be: 1.11
Do you want to expand your list (y/n): y
What do you want the price of the next item to be: 2.22
Do you want to expand your list (y/n): y
What do you want the price of the next item to be: 101
Do you want to expand your list (y/n): y
What do you want the price of the next item to be: 1000000.99
Do you want to expand your list (y/n): n
1: 1.11
2: 2.22
3: 101.00
4: 1000000.99
$
Test it online: https://onlinegdb.com/x1jVUU6GT
My Helper Function, getInput() will read the data into the array list until end of input, where they will read in the Staff ID, total number of leave allowed and the number of days of leave taken so far. It is supposed to return the number of records read through the pointer variable n. However, when I try to dereference the pointer, the program will close and I am not sure why. Thank you in advance
My Code:
#include <stdio.h>
#include <stdlib.h>
#define SIZE 80
typedef struct {
int id; /* staff identifier */
int totalLeave; /* the total number of days of leave allowed */
int leaveTaken; /* the number of days of leave taken so far */
}leaveRecord;
// Function Prototypes
void getInput(leaveRecord list[ ], int *n);
int mayTakeLeave(leaveRecord list[ ], int id, int leave, int n);
void printList(leaveRecord list[ ], int n);
int main(){
int choice, ID, LEAVE, leaveApproval;
int recordsRead = 0;
int *ptr = recordsRead;
leaveRecord list[SIZE];
do{
printf("Please Select one of the following Options:\n");
printf("1: getInput()\n");
printf("2: mayTakeLeave()\n");
printf("3: printList()\n");
printf("4: Quit!!\n");
scanf("%d", &choice);
switch(choice){
case 1:
getInput(list, recordsRead);
printf("Temp is %d", recordsRead);
break;
case 2:
printf("Please Enter the Staff ID:\n");
scanf("%d", &ID);
printf("Please Enter the Number of Days of Leave:\n");
scanf("%d", &LEAVE);
leaveApproval = mayTakeLeave(list,ID,LEAVE, ptr);
switch(leaveApproval){
case -1:
printf("Error!! Staff Member not found!");
break;
case 0:
printf("Leave is not approved");
break;
case 1:
printf("Leave is approved");
break;
}
break;
case 3:
break;
}
}while (choice < 3);
return 0;
}
void getInput(leaveRecord list[ ], int *n){
int option = 0, temp = 0;
int userInput;
while (option == 0){
printf("Please key in the Staff Identifier:\n");
scanf("%d", &list->id);
printf("Please key in the Total Number of Days allowed:\n");
scanf("%d", &list->totalLeave);
printf("Please key in the Number of Days of Leave taken:\n");
scanf("%d", &list->leaveTaken);
printf("Please Key in 1 if you like to stop adding Records:\n");
scanf("%d", &userInput);
if(userInput == 1){
break;
}
temp += 1;
}
// Why does dereferencing a Pointer Variable kill the entire program?
*n = temp;
}
int mayTakeLeave(leaveRecord list[ ], int id, int leave, int n){
int leaveUsed = (leave + list->leaveTaken);
for(int i = 0; i < n; i += 1){
if(list->id == id){
if((leaveUsed < list->totalLeave) || (leaveUsed == list->totalLeave)){
return 1;
}
else{
return 0;
}
}
else{
return -1;
}
}
}
void printList(leaveRecord list[ ], int n){
for(int i = 0; i < n; i += 1){
printf(list);
}
}
void getInput(leaveRecord list[ ], int *n);
Here, In getInput function n is an integer type pointer variable which wants address of integer variable.
But here, getInput(list, recordsRead) you are just sending value of records read.
You have to send address of recordsRead.
getInput(list, &recordsRead)
Also in function printList you are using wrong syntax.
printf(list);
Do this :
printf("%d",list[i]);
or
printf("%d",*(list+i));
I have this silly program with my silly problem. I am a very beginner. Let me tell you what I want to do and what is happening here:
What I want to do: I am basically trying to make a function for input which is named here as inp(). This function will ask for input using these two lines:
printf("Enter the Number: ");
scanf("%d", &dip);
When my program will get the number from the user, it will store that inside a variable, let's say dip and will use this number in our another two functions named squarefn and cubefn. I don't know what's going wrong here. But, I can't use the inp() properly to get the number from user.
Why I want to use the inp() function?: Basically, I just want to keep everything inside each function so whenever I need, I will just call my functions. I created inp() so that, I don't need to ask twice or type twice for input.
**What is the output?: ** It's showing some random value or trash value.
Need more information? Feel free to ask!
#include<stdio.h>
int squarefn(int x);
int cubefn(int cube);
int coic();
int printkor(int printkortesi);
int inp();
int main()
{
coic();
}
int squarefn(int input)
{
input = input * input;
return input;
}
int cubefn(int input)
{
input = input * input * input;
return input;
}
int coic()
{
int coi;
int x;
printf("Which one you want?\n");
printf("1. Square\n");
printf("2. Cube\n");
printf("Enter here: ");
scanf("%d", &coi);
int cubed = cubefn(x);
switch (coi)
{
case 1:
// printf("Enter the Number: ");
// scanf("%d", &x);
inp();
int dear = inp(x);
squarefn(dear);
int squared = squarefn(x);
printkor(squared);
break;
case 2:
printf("Enter the Number: ");
scanf("%d", &x);
cubefn(x);
int cubed = cubefn(x);
printkor(cubed);
break;
default:
printf("Error.");
break;
}
}
int inp()
{
int dip;
printf("Enter the Number: ");
scanf("%d", &dip);
return dip;
}
int printkor(int printkortesi)
{
printf("Printed: %d", printkortesi);
}
There is a lot of redundant code in your program, many of the statements don't do anything except taking CPU time . Read about Function Calls in C. Most of your doubts will be solved after a good read
return_type function_name( parameter list ) {
body of the function
}
You have return type of int, to receive value of function foo
int foo(int x)
{return x*x;}
int main()
{
int y =foo(5); //integer y takes value returned by function foo, that is 5
printf("%d\n",y); // This will print value 25
return 0;
}
Your code altered as below, should work now:
#include<stdio.h>
int squarefn(int x);
int cubefn(int cube);
int coic();
int printkor(int printkortesi);
int inp();
int main()
{
coic();
}
int squarefn(int input)
{
input = input * input;
return input;
}
int cubefn(int input)
{
input = input * input * input;
return input;
}
int coic()
{
int coi;
int x;
printf("Which one you want?\n");
printf("1. Square\n");
printf("2. Cube\n");
printf("Enter here: ");
scanf("%d", &coi);
int cubed = cubefn(x);
int dear = inp();
switch (coi)
{
case 1:
{int squared = squarefn(dear);
printkor(squared);
break;}
case 2:
{int cubed = cubefn(dear);
printkor(cubed);
break;}
default:
printf("Error.");
break;
}
}
int inp()
{
int dip;
printf("Enter the Number: ");
scanf("%d", &dip);
return dip;
}
int printkor(int printkortesi)
{
printf("Printed: %d\n", printkortesi);
}
Edit:
Fixed it, I just noticed there was variable declaration in the switch statement. Case statements are only labels. This means the compiler will interpret this as a jump directly to the label. So I added { } in switch and it should work now.
I'm new to programming so I'm trying to write a small program were I can show car information but also add cars to my "library"
right now my out come for 1.Show cars looks like this:
ID BRAND PICS
bbb188 BMW 1 2 3
AAA-999 VOLVO 4 5 6
CCC-999 CITROEN 1 2 3
but after I add a new car the PICS does not show.
so if I would add AAA-111 VOLVO 1. this is the outcome:
bbb188 BMW 1 2 3
AAA-999 VOLVO 4 5 6
CCC-999 CITROEN 1 2 3
AAA-111 VOLVO -398253632 3 3
I just get random numbers for pics and always 3 values.
Could anyone help me with this, and please show me how to do it instead.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#define MAX 1000
#define IDSIZE 20
#define BRANDSIZE 50
#define PICSIZE 10
typedef struct{
char id[IDSIZE+1];
char brand[BRANDSIZE+1];
int *pic;
} Car;
void printCar(Car *pCar,int imagecount)
{
printf(" %s ",pCar->id);
printf(" %s ",pCar->brand);
for(int i=0; i<imagecount; i++){
printf(" %d",pCar->pic[i]);
}
printf("\n");
}
Car initCar(char itsId[],char itsBrand[],int *itsPic, int imagecount)
{
Car newCar;
strcpy(newCar.id, itsId);
strcpy(newCar.brand, itsBrand);
newCar.pic = itsPic;
return newCar;
}
void PrintList(Car aLista[],int imagecount, int carcount)
{
for(int i = 0; i<imagecount; i++)
printCar(&aLista[i],carcount);
}
void AddCar(Car aList[], int *pAt, Car theCar)
{
aList[(*pAt)++]=theCar;
}
Car NewCar(Car minapatienter[], int patientCount)
{
Car newCar;
gets(newCar.id);
printf("type in ID \n");
gets(newCar.id);
printf("type in brand\n");
gets(newCar.brand);
bool imageInputDone = false;
int imageCount=0;
while(imageInputDone == false)
{
printf("type in image reference \n");
int newImage;
scanf("%d",&newImage);
newCar.pic = &newImage;
imageCount++;
printf("vill du \n1.Add another image reference \n2.exit\n");
int input;
scanf("%d", &input);
printf("input: %i\n",input);
switch(input)
{
case 1:
printf("Adding one more image\n");
break;
case 2:
printf("Leaving loop\n");
imageInputDone = true;
break;
default:
while (input<1 || input<2)
;
printf("Input correct number\n");
break;
}
return newCar;
}
}
int main(void)
{
int carCount=0;
int imagecount=0;
Car myCar[MAX];
int input;
int test[3]={1,2,3};
int test2[3]={4,5,6};
myCar[0]= initCar("bbb188","BMW", test, 3);
myCar[1] = initCar("AAA-999","VOLVO", test2, 3);
myCar[2] = initCar("CCC-999", "CITROEN", test,3);
carCount=3;
imagecount=3;
do {
printf("1. Show cars \n2. Add car \n");
scanf("%d",&input);
switch(input)
{
case 1:
printf("ID BRAND PICS \n");
PrintList(myCar,carCount, imagecount);
break;
case 2:
AddCar(myCar,&carCount,NewCar(myCar,carCount));
printf("ID BRAND PICS \n");
PrintList(myCar,carCount, imagecount);
} //break;
} while (input < '1'|| input < '2');
return 0;
}
Your NewCar function have some problems. The newImage is in stack memory. When you do assignment newCar.pic = &newImage; the newCar.pic will point to undefined memory region because newImage was out of its scope. better way, we just use its value only, don't use address operator here. And one more thing, the newCar.pic is an pointer (array of int). So you need to allocate it before use. When you add more image item, you need to reallocate it. And initialize the pic to NULL pointer as well.
Here is my modification your NewCar function:
Car NewCar(Car minapatienter[], int patientCount)
{
Car newCar;
gets(newCar.id);
printf("type in ID \n");
gets(newCar.id);
printf("type in brand\n");
gets(newCar.brand);
newCar.pic = NULL;
bool imageInputDone = false;
int imageCount=0;
while(imageInputDone == false)
{
printf("type in image reference \n");
int newImage;
scanf("%d",&newImage);
// Rellocation
newCar.pic = realloc(newCar.pic, (imageCount+1)*sizeof(int));
newCar.pic[imageCount] = newImage;
imageCount++;
printf("vill du \n1.Add another image reference \n2.exit\n");
int input;
scanf("%d", &input);
printf("input: %i\n",input);
switch(input)
{
case 1:
printf("Adding one more image\n");
break;
case 2:
printf("Leaving loop\n");
imageInputDone = true;
break;
default:
while (input<1 || input<2)
;
printf("Input correct number\n");
break;
}
return newCar;
}
}
You get the same number of images printed for each car because you only have a global counter. You need a counter per image:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#define MAX 1000
#define IDSIZE 20
#define BRANDSIZE 50
#define PICSIZE 10
typedef struct Car
{
char id[IDSIZE+1];
char brand[BRANDSIZE+1];
int *pic;
int imagecount;
} Car;
With this change there is no need to pass a count for printing:
void printCar(Car *pCar)
{
printf(" %s ", pCar->id);
printf(" %s ", pCar->brand);
for(int i=0; i<pCar->imagecount; i++)
{
printf(" %d",pCar->pic[i]);
}
printf("\n");
}
The counter needs to be stored during initialization:
Car initCar(char itsId[], char itsBrand[], int *itsPic, int imagecount)
{
Car newCar;
strcpy(newCar.id, itsId);
strcpy(newCar.brand, itsBrand);
newCar.pic = itsPic;
newCar.imagecount = imagecount;
return newCar;
}
When you print your list, you mix up count of images and count of cars:
void PrintList(Car aLista[], int imagecount, int carcount)
{
for(int i = 0; i<imagecount; i++)
printCar(&aLista[i],carcount);
}
This must be:
void PrintList(Car aLista[], int carcount)
{
for (int i = 0; i < carcount; i++)
printCar(&aLista[i]);
}
Adding the car to your array is basically OK, but you might check if you reach MAX cars.
void AddCar(Car aList[], int *pAt, Car theCar)
{
aList[(*pAt)++]=theCar;
}
Now the biggest problem. This function hads issues with memory usage and weird loops.
Car NewCar(void)
{
Car newCar = {0}; // initialze with empty strings and NULL pointers.
// TODO: Replace gets with fgets!
// gets(newCar.id); // WHY read before you prompt??
printf("type in ID \n");
gets(newCar.id);
printf("type in brand\n");
gets(newCar.brand);
bool imageInputDone = false;
int imageCount=0;
while(imageInputDone == false)
{
printf("type in image reference \n");
int newImage;
scanf("%d",&newImage);
imageCount++;
int *newpics = realloc(newCar.pic, (imageCount) * sizeof(int));
newpics[imageCount-1] = newImage;
newCar.pic = newpics;
// TODO: Check for NULL
printf("vill du \n1.Add another image reference \n2.exit\n");
int input;
scanf("%d", &input);
printf("input: %i\n",input);
while (input < 1 || input > 2)
switch(input)
{
case 1:
printf("Adding one more image\n");
break;
case 2:
printf("Leaving loop\n");
imageInputDone = true;
break;
default:
printf("Input correct number\n");
break;
}
newCar.imagecount = imageCount;
return newCar;
}
}
And finally...
int main(void)
{
int carCount=0;
Car myCar[MAX];
int input;
int test[3] = {1,2,3};
int test2[3] = {4,5,6};
myCar[0] = initCar("bbb188", "BMW", test, 3);
myCar[1] = initCar("AAA-999", "VOLVO", test2, 3);
myCar[2] = initCar("CCC-999", "CITROEN", test, 3);
carCount=3;
do
{
printf("1. Show cars \n2. Add car \n");
scanf("%d", &input);
switch(input)
{
case 1:
printf("ID BRAND PICS \n");
PrintList(myCar, carCount);
break;
case 2:
AddCar(myCar, &carCount, NewCar());
printf("ID BRAND PICS \n");
PrintList(myCar, carCount);
} //break;
} while (input < 1 || input > 2); // compare as integers, not characters. Don't use < operator
return 0;
}
The code is not tested. Remaining errors are left for exercise. ;)
After user choose their pizza,they can't choose their side order as the menu for side order are missing.
Is there anything wrong with the looping?
It is suspected to have something to do with while looping.
int main()
{
int cont;
int cust;
int i;
int j;
double side=0.00;
double pizza=0.00;
double total=0.00;
for(cust=0;cust<5;cust++)
{
printf("Welcome To Pizza Hut\n");
printf("Pizza Menu :\n");
printf("1=Chicken\n");
printf("2=Meat\n\n");
printf("Enter Pizza Flavor : ");
scanf("%d",&i);
if(i==1)
{
pizza=5.50;
}
if(i==2)
{
pizza=4.50;
}
while(cont==1) /*This is where the menu for side order didn't show*/
{
printf("Side Order Menu :\n");
printf("1=coke\n");
printf("2=pepsi\n");
printf("3=bread\n");
printf("4=salad\n\n");
printf("Enter Side Order : ");
scanf("%d",&j);
if(j==1)
{
side=1.50;
}
if(j==2)
{
side=1.30;
}
if(j==3)
{
side=2.50;
}
if(j==4)
{
side=2.60;
}
printf("Add Order? (1=yes||0=no) : ");
scanf("%d",&cont);
}
}
total=pizza+side;
printf("Total : %.2f",total);
cust++;
return 0;
}
Here, you haven't given a value to the cont variable so while loop doesn't properly work.
I think there are some errors:
You should initialize the cont variable to 1
You should to add a breaking mechanism inside your while loop in order to escape from it
You should reset your cont variable to 1 after the while loop again.
This might should work:
int main()
{
int cont = 1;
int cust;
int i;
int j;
double side=0.00;
double pizza=0.00;
double total=0.00;
for(cust=0;cust<5;cust++)
{
printf("Welcome To Pizza Hut\n");
printf("Pizza Menu :\n");
printf("1=Chicken\n");
printf("2=Meat\n\n");
printf("Enter Pizza Flavor : ");
scanf("%d",&i);
if(i==1)
{
pizza=5.50;
}
if(i==2)
{
pizza=4.50;
}
while( cont == 1 ) /*This is where the menu for side order didn't show*/
{
printf("Side Order Menu :\n");
printf("1=coke\n");
printf("2=pepsi\n");
printf("3=bread\n");
printf("4=salad\n\n");
printf("Enter Side Order : ");
scanf("%d",&j);
if(j==0)
{
cont = 0;
break;
}
if(j==1)
{
side=1.50;
}
if(j==2)
{
side=1.30;
}
if(j==3)
{
side=2.50;
}
if(j==4)
{
side=2.60;
}
printf("Add Order? (1=yes||0=no) : ");
scanf("%d",&cont);
}
cont = 1;
}
total=pizza+side;
printf("Total : %.2f",total);
cust++;
return 0;
}
Where you have the line int cont;, replace it with int cont=1;. cont will have indeterminate value, so you'll never enter the loop to set it to anything else.
If I'm not wrong, when you say
while(cont==1)
You're saying, while cont it's equals to 1, proceed, and cont is never 1.
You have to initialize the variable count to 0 too.