1. Limited time only! Sign up for a free 30min personal tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Using pointers in a User Define Function

  1. Oct 17, 2011 #1
    1. The problem statement, all variables and given/known data

    There is a user defined function that looks like this:
    void DisplayMenu(char *item)

    My problem is that I have no clue on how I could include "*item" in my function, without changing the name or algorithm. The purpose of this function to to display the list of apps available and to prompts for the user’s selection and to sets the value of the selection.


    2. Relevant equations
    Here is the whole equation:
    void DisplayMenu(char *item)
    {
    double G;
    double X;
    double E;
    double R;
    double P;

    double GamePackage=4.99;
    double XRayApp=2.99;
    double EBayAutobidder=7.99;
    double RestaurantLocator=1.99;
    double Photoeditor=3.99;

    printf("HERE ARE THE SELECTION:\n");
    printf("G -- GamePackage %.2lf\n",GamePackage);
    printf("X -- X-Ray App %.2lf\n",XRayApp);
    printf("E -- E-Bay Autobidder %.2lf\n",EBayAutobidder);
    printf("R -- Restaurant Locator %.2lf\n",RestaurantLocator);
    printf("P -- Photo editor %.2lf\n",Photoeditor);
    return;

    }



    3. The attempt at a solution
    The user must type in the letter of the selection, such as G, X, E, R, or P. I think this is where the char *item must be used, but how can I use it store what the user selects?

    Any help is very much appreciated!
     
  2. jcsd
  3. Oct 17, 2011 #2

    Mark44

    Staff: Mentor

    When you submit a code example, put [ code] tag just before the beginning and a [ /code] tag after the end (omit the extra spaces, though).
    This is not an equation - this is the code for the function you wrote.
    You don't need any of your G, X, E, R, or P double variables. All you need is a single char variable that will hold the letter that a user of your program enters.

    You also need a statement that takes input from the user to set that char variable.

    C is a "pass by value" language, which means that functions work with copies of the parameters in the argument list. To simulate "call by reference," functions pass the address of a variable in the argument list. Your textbook or notes should have some explanation of this technique, which is how your function should work.
     
  4. Oct 17, 2011 #3
    Thank you for the response.

    Here's the problem now, I'm trying to get the DisplayMenu to display on the user's screen, but there are errors that I don't know how to to fix.

    Here is the new code
    Code (Text):
    void DisplayMenu(char *item)
    {
        char UserSelection;
        *item;
        UserSelection=*item;



        printf("HERE ARE THE SELECTION:\n");
        printf("G -- GamePackage            $4.99\n");
        printf("X -- X-Ray App              $2.99\n");
        printf("E -- E-Bay Autobidder       $7.99\n");
        printf("R -- Restaurant Locator     $1.99\n");
        printf("P -- Photo editor           $3.99\n");
        scanf(" %c", &UserSelection);

        return;

    }
     
    and here is what I put in the int main area

    Code (Text):


    int *ptr;
    int main()
    {
        char UserChoice;
        double Bank;
        int MoneyMenu;
        ptr=0;
        double UserMoneyAmount;

        printf("Welcome to THE APP STORE.\n**********************************\n");
        DisplayMenu(ptr);

    }
    The DisplayMenu(ptr) is incorrect but I don't know what I can put inside the (). I tried putting char and int variables to see if it works but it doesn't. Thanks again!
     
  5. Oct 18, 2011 #4
    You shouldn't just guess for something like that. What types a function takes as arguments inside the parenthesis can be determined by examining the function header or function prototype.

    Code (Text):

    void DisplayMenu(char *item)
     
    This function header indicates a function called DisplayMenu that takes a pointer to char, a.k.a. char* as an argument.
     
  6. Oct 18, 2011 #5

    Mark44

    Staff: Mentor

    I have added comments in your code.
    Code (Text):

    void DisplayMenu(char *item)
    {
        char UserSelection; // You don't need this variable.
        *item;   // This line does nothing so it should be here.
        UserSelection=*item; // You don't need to do this. UserSelection gets set below.



        printf("HERE ARE THE SELECTION:\n");
        printf("G -- GamePackage            $4.99\n");
        printf("X -- X-Ray App              $2.99\n");
        printf("E -- E-Bay Autobidder       $7.99\n");
        printf("R -- Restaurant Locator     $1.99\n");
        printf("P -- Photo editor           $3.99\n");
        scanf(" %c", &UserSelection); // See explanation following code block.

        return;  // Take this line out. The function will return anyway.

    }
    For your input line, I would do it this way:
    Code (Text):
    scanf("%c", item);
    item already is a pointer to a char, so you don't need the "address of" operator, &. Note that I removed the extra space you had in the format specifier string for scanf. I.e., " %c" is now "%c".
     
  7. Oct 20, 2011 #6
    Hi guys, I finally had my menu being able to displayed. Now my other problem is getting the cost to be whatever the user wants from the menu. My user function for the code that set's user choice is this:
    Code (Text):
    void SetCost(char item, double *item_cost)
        {
            //The variable that represents amount of money user has
            double Bank;

            //Costs of items
            double G=4.99;
            double X=2.99;
            double E=7.99;
            double R=1.99;
            double P=3.99;

            char G;
            char X;
            char E;
            char R;
            char P;
            if(item_cost<0)
            {
                printf("You picked %c, which cost %d.", item, item_cost);
            }

        }
    that is what I have set up so far and I'm not even sure if I'm on the right track. What also confuses is that this user function has two argument, yet from my other code which is right here:

    Code (Text):

    // Displays the list of apps available
    //prompts for the user’s selection and sets the value of the selection
    void DisplayMenu(char *item)
    {
        char Menu;
        double *MenuCost;

        //Menu with costs
        printf("HERE ARE THE SELECTION:\n");
        printf("G -- GamePackage            $4.99\n");
        printf("X -- X-Ray App              $2.99\n");
        printf("E -- E-Bay Autobidder           $7.99\n");
        printf("R -- Restaurant Locator         $1.99\n");
        printf("P -- Photo editor           $3.99\n");

        //Asks for user's selection
        printf("\nPlease choose your selection: ");

        //User will enter their desired item
        scanf("%c", item);
        SetCost(Menu, MenuCost);

    }
    You can see that the scanf only scans one variable in DisplayMenu, so how is that suppose to transfer to the SetCost function with just one argument?
     
  8. Oct 20, 2011 #7

    Mark44

    Staff: Mentor

    It is a bad design to have variables in one place with the item prices (in the SetCost function) and have the prices hard-coded in another (in the strings in GetMenu). This makes the program more difficult to maintain if the item prices change - you have to remember to change the price in both places.

    It's probably reasonable to have global constants for the prices; i.e. constants that are defined outside of all functions so they can be used throughout your program.

    Your DisplayMenu function has a name that is misleading. It not only displays a menu, but it gets the user's menu choice. A better way to do things would be to have DisplayMenu just display the menu, and write another function to get the user's menu choice (name might be GetMenuChoice). Then your SetCost function could determine the item's cost based on the menu item that the user chose.
     
    Last edited: Oct 21, 2011
  9. Oct 21, 2011 #8
    I wish I could but I'm not allowed to add another function. My SetCost function is supposed to sets the cost of the item based on value stored in purchase but I've been staring at the code for an hour and am clueless. Here is what I have now:
    Code (Text):
    void DisplayMenu(char *item)
    {
        char UserSelection;
        double CostOfItem;
        //Menu with costs
        printf("HERE ARE THE SELECTION:\n");
        printf("G -- GamePackage            $4.99\n");
        printf("X -- X-Ray App              $2.99\n");
        printf("E -- E-Bay Autobidder           $7.99\n");
        printf("R -- Restaurant Locator         $1.99\n");
        printf("P -- Photo editor           $3.99\n");
        //Asks fo   r user's selection
        printf("\nPlease choose your selection: ");
        //User will enter their desired item
        scanf("%c", &UserSelection);
        SetCost(UserSelection, &CostOfItem);
    }
     
    EDIT: Nvm, I have decided to put SetCost in my main function, don't think it was possible to have two argument functions in a one way argument function.
     
    Last edited: Oct 21, 2011
  10. Oct 21, 2011 #9

    Mark44

    Staff: Mentor

    From an earlier post:
    You are trying to make the DisplayMenu function do too much. I don't think you have given enough thought to what your main function will be doing.

    As already mentioned, the name of the DisplayMenu function is misleading, as it not only displays a menu but gets the user's selection. If that's the name you have to use, and what it has to do, then I guess you're stuck with it, and the blame for poor design goes to your instructor.

    In any case, your implementation of DisplayMenu doesn't set its parameter, and it should not be calling SetCost.

    Here's a rough idea of how I would arrange things.

    Code (Text):

    #include <stdio.h>
    // Other includes as needed

    // Global constants for item prices
    double GamePackagePrice=4.99;
    double XRayAppPrice=2.99;
    double EBayAutobidderPrice=7.99;
    double RestaurantLocatorPrice=1.99;
    double PhotoeditorPrice=3.99;

    // Function prototypes
    void DisplayMenu(char *);
    void SetCost(char, double *);




    int main()
    {
       // Skeleton outline of main function

       // Display menu and get user's selection
       // Get price of user's selection
       // Display price of item to user
       return 0;
    }

    void DisplayMenu(char * item)
    {
       // Display menu with costs
       printf("HERE ARE THE SELECTIONS:\n");
       printf("G -- GamePackage         %lf\n", GamePackagePrice);
       printf("X -- X-Ray App               %lf\n", XRayAppPrice);
       // Display the other menu choices

       // Ask for user's selection
       printf("\nPlease choose your selection: ");

       // User will enter their desired item
       scanf("%c", &item);
    }

    void SetCost(char item, double *item_cost)
    {
    }



     
     
  11. Oct 23, 2011 #10
    You're right Mark, it isn't going to set any parameter nor call the SetCost function. My teacher also said that we can't use global variables, we have to fit them in the right user function elsewhere.. I'll figure that out on my own.

    This is where I'm stuck with the SetCost function, I need to compare the item, which is a char, and with that char I want to find. I need to match it up. When I find it, I need to set the value of item_cost with the right cost. Here is what I did:

    Code (Text):
    void SetCost(char item, double *item_cost)
        {
        double MoneyInBank;
        char G=4.99;
        char X=2.99;
        char E=7.99;
        char R=1.99;
        char P=3.99;
        if(item==G)
        {
            MoneyInBank=MoneyInBank-G;
            if(MoneyInBank<0)
            {
                printf("You do not have enough money");
            }
            else if(MoneyInBank>0)
            {
            printf("You have %d left over", MoneyInBank);
            }  
        }
    Here is the rest of the code of where I drew the user's char from:
    Code (Text):
    int main()
    {
        char ChoiceSelection;
        double ItemCost;
        double bank;
        bank=0;

        //Variable that keeps  track of user's money
        //User starts with no money, so variable is initlize to zero
        printf("Welcome to THE APP STORE.\n**********************************\n");
        printf("You have $%.2lf in your bank\n\n", bank);
        DisplayMenu(&ChoiceSelection);
        SetCost(ChoiceSelection, &ItemCost);

    }

    // Displays the list of apps available
    //prompts for the user’s selection and sets the value of the selection
    void DisplayMenu(char *item)
    {

        //Menu with costs
        printf("HERE ARE THE SELECTION:\n");
        printf("G -- GamePackage            $4.99\n");
        printf("X -- X-Ray App              $2.99\n");
        printf("E -- E-Bay Autobidder           $7.99\n");
        printf("R -- Restaurant Locator         $1.99\n");
        printf("P -- Photo editor           $3.99\n");
        //Asks for user's selection
        printf("\nPlease enter a selection: ");
        //User will enter their desired item
        scanf("%c", item);
       

    }
    I know that a char isn't compatible with a double variable, so how else can I approach this?
     
  12. Oct 23, 2011 #11

    Mark44

    Staff: Mentor

    There are several things wrong with this code.
    1) Your char variables G, X, and so on are not the right type to store a double in. The variables should be type double.
    2) Your names for the app prices should be more informative, and should NOT be single letters. For example, you should do something like this:
    double GamePackagePrice = 4.99;
    3) SetCost is not setting the item_cost variable. You need logic in this function that determines which app was selected, and then sets item_cost. See below for an example.
    4) The MoneyInBank variable is uninitialized, so any calculations that use it are going to result in garbage values. I don't think you should be checking the user's account balance in the SetCost function. That should probably be done in main or possibly in another function. Speaking of the user's account balance ("bank" is a silly name for the variable), it is set to 0 in main, and nothing else is done to increase this value, so the user will never have enough money to be able to buy one of the apps.

    For #3 above, something like this would work in the SetCost function.
    Code (Text):

    .
    .
    .
    double GamePackagePrice = 4.99;
    .
    .
    .
    if (item == 'G') *item_cost = GamePackagePrice;
    else if (item == 'X') *item_cost = XRayAppPrice;
    // and so on.
     
    The code above doesn't work if the item is a lower-case letter, like 'g' or 'x'. It's pretty easy to add these possible values in the logic above.
     
  13. Oct 23, 2011 #12
    That definitely helps! I tried printing the price cost and I keep getting either big or negative numbers instead of 4.99. here's what I put:

    if(item=='G'||item=='g')
    {
    *item_cost=GamePackagePrice;
    printf("The price is %d\n", *item_cost);
    }

    I tried changing the * and & around, but no luck, what is the problem here?
     
  14. Oct 23, 2011 #13

    Mark44

    Staff: Mentor

    Show me the rest of your SetCost function.
     
  15. Oct 23, 2011 #14
    Code (Text):
    void SetCost(char item, double *item_cost)
        {
        double ItemWanted=0;
        double GamePackagePrice=4.99;
        double XRayAppPrice=2.99;
        double EBayAutobidderPrice=7.99;
        double RestaurantLocatorPrice=1.99;
        double PhotoEditorPrice=3.99;
        if(item=='G'||item=='g')
        {
            *item_cost=GamePackagePrice;
            printf("The price is %d\n", *item_cost);
        }
        else if(item=='X'||item=='x')
        {
            *item_cost=XRayAppPrice;
            printf("The price is %d", *item_cost);
        }
        else if(item=='E'||item=='e')
        {
            *item_cost=EBayAutobidderPrice;
            printf("The price is %d", *item_cost);
        }
        else if(item=='R'||item=='r')
        {
            *item_cost=RestaurantLocatorPrice;
            printf("The price is %d", *item_cost);
        }
        else if(item=='P'||item=='p')
        {
            *item_cost=PhotoEditorPrice;
            printf("The price is %d", *item_cost);
        }
        else
            printf("Please re enter in the choice");
        return ItemWanted;
    }
    Yes, I know I need to fix the return thing lol.
     
  16. Oct 23, 2011 #15

    Mark44

    Staff: Mentor

    Your printf statements have the wrong format specifiers - %d. This formatspecifier is used to display an int. Your prices are doubles, so use %f.
    Code (Text):
    printf("The price is %f\n", *item_cost);
     
  17. Oct 23, 2011 #16
    Now I've ran to similar problems.. except with doubles this time!
    Code (Text):

    //Displays the codes for money input- gets user input amounts
    //compares the int codes and updates the deposit amount
    void MoneyMenu(double *bank, double item_cost)
    {
       
        //Money Menu List
        printf("Please credit your bank balance by selecting from the menu:\n\n");
        printf("--- 1   $10.00\n");
        printf("--- 2   $5.00\n");
        printf("--- 3   $2.00\n");
        printf("--- 4   $1.00\n");
        scanf("%f", bank);
        if(bank=='1')
        {


       
    }
     
    I can't translate the number "1" to be10.00 , how would you do this? the if statement will not cut it this time.

    For instance, although the user picks the number "1", that means that they'll deposit 10, but I need to format it in the programming pseudocode.
     
  18. Oct 23, 2011 #17

    Mark44

    Staff: Mentor

    You really should change the variable named bank - it is a meaningless name in the context of your program. Names for variables should reflect what they are being used for. A better name would be accountBalance, for example.

    Think about what MoneyMenu is doing. It's presenting a menu with four choices. A user will enter 1, 2, 3, or 4, which scanf can read as ints.

    If the user enters 1, the account balance should be credited with (incremented by) $10. And similarly for the other four choices.
     
  19. Oct 24, 2011 #18
    Unfortunately I cannot change the variables :( we have to use as what it is.

    I am almost done with the program! One problem is that some function like CheckMoney , GetMoney, and GetChange doesn't do what they are intended to do. I believe I have the code somewhere messed up. Here's what I've done (the complete program)
    Code (Text):
    #include <stdio.h>
    void DisplayMenu(char *item);
    void SetCost(char item, double *item_cost);
    void MoneyMenu(double *bank, double item_cost);
    int CheckMoney(double bank, double item_cost);
    void GetMoney(double *bank, double item_cost, char item);  
    void GetChange(double *bank, double item_cost);
    void Quit(char *again);


    int main()
    {
        //Variable implanted to see if user wants to play again
        char PlayAgain;
        //Variable that decides what the user wants from menu
        char ChoiceSelection;
        //Variable that tells us the cost of item
        double ItemCost;
        //Variable that holds the bank balance
        double BankBalance;
        //initializes to zero as starting point
        BankBalance=0;

        //Variable that keeps  track of user's money
        //User starts with no money, so variable is initlize to zero
        printf("Welcome to THE APP STORE.\n**********************************\n");
        printf("You have $%.2lf in your bank\n\n", BankBalance);
        DisplayMenu(&ChoiceSelection);
        SetCost(ChoiceSelection, &ItemCost);
        GetMoney(&BankBalance,ItemCost,ChoiceSelection);
        Quit(&PlayAgain);
    }

    // Displays the list of apps available
    //prompts for the user’s selection and sets the value of the selection
    void DisplayMenu(char *item)
    {

        //Menu with costs
        printf("HERE ARE THE SELECTION:\n");
        printf("G -- GamePackage            $4.99\n");
        printf("X -- X-Ray App              $2.99\n");
        printf("E -- E-Bay Autobidder           $7.99\n");
        printf("R -- Restaurant Locator         $1.99\n");
        printf("P -- Photo editor           $3.99\n");
        //Asks for user's selection
        printf("\nPlease enter a selection: ");
        //User will enter their desired item
        scanf("%c", item);
       

    }

    //sets the cost of the item based on value stored in purchase
    void SetCost(char item, double *item_cost)
    {
        //names set to equal to price
        double GamePackagePrice=4.99;
        double XRayAppPrice=2.99;
        double EBayAutobidderPrice=7.99;
        double RestaurantLocatorPrice=1.99;
        double PhotoEditorPrice=3.99;
        //if user enters G or g, the correct price is given
        if(item=='G'||item=='g')
        {
            *item_cost=GamePackagePrice;
            printf("The price is %.2f\n ",*item_cost);
        }
        //if user enters X or x, the correct price is given
        else if(item=='X'||item=='x')
        {
            *item_cost=XRayAppPrice;
            printf("The price is %.2f\n ",*item_cost);
        }
        //if user enters E or e, the correct price is given
        else if(item=='E'||item=='e')
        {
            *item_cost=EBayAutobidderPrice;
            printf("The price is %.2f\n ",*item_cost);
        }
        //if user enters R or r, the correct price is given
        else if(item=='R'||item=='r')
        {
            *item_cost=RestaurantLocatorPrice;
            printf("The price is %.2f\n ",*item_cost);
        }
        //if user enters P or p, the correct price is given
        else if(item=='P'||item=='p')
        {
            *item_cost=PhotoEditorPrice;
            printf("The price is %.2f\n ",*item_cost);
        }
    }

    //Displays the codes for money input- gets user input amounts
    //compares the int codes and updates the deposit amount
    void MoneyMenu(double *bank, double item_cost)
    {
       
        //Money Menu list that user choose in order to get money to buy item
        printf("Please credit your bank balance by selecting from the menu:\n\n");
        printf("--- 1   $10.00\n");
        printf("--- 2   $5.00\n");
        printf("--- 3   $2.00\n");
        printf("--- 4   $1.00\n");
        //scans how much they want
        scanf("%d", bank);
        //if they picked 1, they will be credited 10 dollars
        if(*bank==1)
        {
            bank=bank+10;
        }
        //if they picked 2, they will be credited 5 dollars
        else if(*bank==2)
            {
            bank=bank+5;
        }
        //if they picked 3, they will be credited 2 dollars
            else if(*bank==3)
                {
            bank=bank+2;
        }
        //if they picked 4, they will be credited 1 dollar
            else if(*bank==4)
                {
            bank=bank+1;
        }
           


       
    }

    //compares the amount the user has in deposits to the price of item selected.
    //It returns 1 if the amount is enough to cover the cost, 0 if there is not enough.
    int CheckMoney(double bank, double item_cost)
    {
        //if they have enough money to cover the cost of item, it returns 1 to let them buy
        if(bank>=item_cost)
        {
            bank=bank-item_cost;
            return 1;
        }
        //if they don't have enough money to cover the cost of item, it returns 0 andd they will need to deposit more money
        else if(bank<item_cost)
        {
            printf("You do not have enough in your bank.\n");
            printf("The item costs $%f", item_cost);
            return 0;
        }
    }

    //uses MoneyMenu function to display and collect dollar amounts from the user
    //uses CheckMoney function to keep comparing the added deposited amount to the item cost.
    void GetMoney(double *bank, double item_cost, char item)
    {

        MoneyMenu(bank,item_cost);
        CheckMoney(*bank, item_cost);
       
    }

    //calculates the amount of leftover from your deposits
    void GetChange(double *bank, double item_cost)
    {
        *bank=bank-&item_cost;
        return;
    }

    //Asks the user if they want another app
    void Quit(char *again)
    {
        printf("Would you like to play another game? ");
        scanf("%c", &again);
        if(*again=='y'||*again=='yes'||*again=='Y'||*again=='Yes')
        {
            return;
        }
        else if(*again=='n'||*again=='no'||*again=='N'||*again=='No')
            printf("Thank you, enjoy your purchase(s)");
    }
    It complies and run but doesn't follow the user functions at all.
     
  20. Oct 24, 2011 #19

    Mark44

    Staff: Mentor

    Baloney. You can name the variables what you want. What you can't change are the names of the functions and the types of their arguments.

    For example, the header for the MoneyMenu function says that the first parameter is type pointer to double, and the second parameter is type double. You can name them whatever you want.
    Code (Text):
    void MoneyMenu(double *bank, double item_cost)
     
    My point about bank being a dumb name for a variable is that the name is confusing, and it has confused you.

    Code (Text):
    void MoneyMenu(double *bank, double item_cost)
    {
       
        //Money Menu list that user choose in order to get money to buy item
        printf("Please credit your bank balance by selecting from the menu:\n\n");
        printf("--- 1   $10.00\n");
        printf("--- 2   $5.00\n");
        printf("--- 3   $2.00\n");
        printf("--- 4   $1.00\n");
        //scans how much they want
        scanf("%d", bank); // NO! You need a different variable.
                 //if they picked 1, they will be credited 10 dollars
        if( <something>==1)
        {
            bank=bank+10;
        }
                 .
                 .
                 .
    1. bank is a pointer to double. Your code should have a different local variable of type int to hold the user's choice from the menu.
    2. You are not using bank correctly when you increment it. It's a pointer to a memory location (i.e., a pointer), so to change what the pointer is pointing at, you have to dereference the pointer. The code in your if clause above needs to be changed to this:
    Code (Text):
    *bank = *bank + 10.0;
    And similarly for all the other if clauses.
     
  21. Oct 24, 2011 #20

    Mark44

    Staff: Mentor

    I'm not sure you really understand how C and C++ can modify parameters to functions, so I'm including a simple example. Can you predict what value gets displayed in main?

    The short answer is that C/C++ can't modify parameters to functions, but if the parameter is a pointer to memory, the function can change what's in memory, even though the parameter itself has not been changed. (The pointer still points to the same location in memory.)
    Code (Text):

    #include <stdio.h>
    void modifyParameter(int *);

    int main(void)
    {
       int x = 5;
       modifyParameter(&x);
       printf("New value is %d.\n", x);
       return 0;
    }

    void modifyParameter(int * value)
    {
       *value = 2 * (*value);
    }

     
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook