Problem: Functions

This is a discussion on Problem: Functions within the C Programming forums, part of the General Programming Boards category; Hi everyone. I have just started learning C and encountered problem with functions. Here is my code, it compiles successfully, ...

  1. #1
    Registered User
    Join Date
    Nov 2005
    Posts
    13

    Problem: Functions

    Hi everyone.
    I have just started learning C and encountered problem with functions.
    Here is my code, it compiles successfully, but gives me a runtime error.
    So, please, don't just correct a mistake but also could you please explain what caused it. Thanks in advance.

    Code:
    #include <stdio.h>
    
    void getBalance(int *p_balance);
    
    int main()
    {
      
      int balance/*, serviceCharge*/;
      getBalance(&balance);
      
      getchar();
      return 0;
    }
    
    void getBalance(int *p_balance)
    {
      printf("Welcome to the Cheque Book Balancer\n\n");
      printf("Please enter the current balance: ");
      scanf("%d\n\n", *p_balance);
      printf("*******************************************************");
      printf("Balance forward                                     %d\n", *p_balance);
      printf("*******************************************************");
    }

  2. #2
    Gawking at stupidity
    Join Date
    Jul 2004
    Location
    Oregon, USA
    Posts
    3,164
    scanf() expects all of its parameters to be pointers. So if you had an int you'd do something like:
    Code:
    {
      int a;
    
      scanf("%d", &a);
    }
    However, if you already have a pointer then you don't need to pass the address of that pointer to scanf(), you just pass the pointer:
    Code:
    {
      int a;
      int *p_a = &a;
    
      scanf("%d", p_a);
    }
    &a and p_a are the same. They both evaluate to the address of a which is what scanf() needs.

    You're passing a pointer to balance to your function so you just need to pass that pointer to scanf(). Instead, you're dereferencing that pointer. Try taking the * out from in front of p_balance in the scanf() call. Leave it in the printf() call though since you don't want to print the address of balance you want to print the value stored at that memory address.
    If you understand what you're doing, you're not learning anything.

  3. #3
    Registered User
    Join Date
    Nov 2005
    Posts
    13
    itsme86
    thanks, now I understand it perfectly. scanf() needs a location of a variable (p_balance) not an actiual value stored in the variable.

    However, when I run corrected code it asks me to input a number and then just stops and does not print anything. Do you know what the problem might be? Thanks

  4. #4
    Registered User TactX's Avatar
    Join Date
    Oct 2005
    Location
    Germany.Stuttgart
    Posts
    65
    You propably still have the \n\n in your scanf() call. Remove them.

  5. #5
    Registered User
    Join Date
    Nov 2005
    Posts
    13
    Ok, here is another problem.
    Why can't the function call itself if I use pointers. I know that it works with variabels (recursion). If I can't do it this way could you tell me an alternative.
    Code:
    void updateDeposit(double *p_balance, double *p_deposit, int *p_deposits)
    {
      if(*p_deposit>=0){
      printf("Enter amount of deposit: ");
      scanf("%lf", p_deposit);
      *p_balance = *p_balance + *p_deposit;
      *p_deposits = *p_deposits + 1;
      printf("\n");
      printf("Transaction       Debit       Credit         Balance\n");
      printf("****************************************************\n");
      printf("Cheque                        %.2lf           %.2lf\n", *p_deposit, *p_balance);
      printf("****************************************************\n\n");}
      else{
      printf("Invalid amount!\n");
      updateDeposit(*p_balance, *p_deposit, *p_deposits);} 
      
    }

  6. #6
    cwr
    cwr is offline
    Registered Luser cwr's Avatar
    Join Date
    Jul 2005
    Location
    Sydney, Australia
    Posts
    868
    A function can call itself if you use pointers.

    The problem is that your call is incorrect:
    Code:
    updateDeposit(*p_balance, *p_deposit, *p_deposits);}
    When you use an * outside of a declaration, it means dereference the pointer. You shouldn't have the *'s when you call the function, only in the declaration.

    Also, please indent your code properly.

  7. #7
    Registered User
    Join Date
    Nov 2005
    Posts
    13
    Thanks everyone for help. However here is another problem I got with "while loop". Before even getting input from user it goes straight to "else" and executes whatever is in there. I ran through the program and I don't see where the problem is.

    Code:
    .
    .
    .
    while((trans = getTrans()) != 'q')
      {
        
        if (trans == 'c' || trans == 'C'){
          updateCheque(&balance, &cheque, &cheques, &bounced);
          transMenu();
        }
        else if(trans == 'd' || trans == 'D'){
          updateDeposit(&balance, &deposit, &deposits);
          transMenu();
        }
        else if(trans == 'w' || trans == 'W'){
          updateWithdrawal(&balance, &withdrawal, &withdrawals);  
          transMenu();
        }
        else
          printf("Invalid selection, enter 'c', 'd', 'w', or 'q': ");    
          
      }
    .
    .
    .
    char getTrans()
    {
      char ch;
      scanf("%c", &ch);
      return ch;
    }
    cwr
    Also, please indent your code properly.
    Is this good enough?

  8. #8
    Registered User
    Join Date
    Nov 2005
    Posts
    13
    If you don't know what I mean by my previous post, here is the whole program. Run it and see for yourself. So does anyone know what the problem is?

    Code:
    #include <stdio.h>
    
    void getBalance(double *p_balance);
    void transMenu();
    char getTrans();
    void updateCheque(double *p_balance, double *p_cheque, int *p_cheques, int *p_bounced);
    void updateDeposit(double *p_balance, double *p_deposit, int *p_deposits);
    void updateWithdrawal(double *p_balance, double *p_withdrawal, int *p_withdrawals);
    void updateServiceCharge(double *p_balance, double *p_serviceCharge, int *p_cheques, int *p_bounced, int *p_deposits, int *p_withdrawals);
    
    int main()
    {
      int bounced = 0, deposits = 0, cheques = 0, withdrawals = 0;
      double balance, serviceCharge, cheque, deposit, withdrawal;
      char trans;
      getBalance(&balance);
      transMenu();
          
      while((trans = getTrans()) != 'q' && trans !='Q')
      {
        if (trans == 'c' || trans == 'C'){
          updateCheque(&balance, &cheque, &cheques, &bounced);
          transMenu();
        }
        else if(trans == 'd' || trans == 'D'){
          updateDeposit(&balance, &deposit, &deposits);
          transMenu();
        }
        else if(trans == 'w' || trans == 'W'){
          updateWithdrawal(&balance, &withdrawal, &withdrawals);  
          transMenu();
        }
        else
          printf("Invalid input!\tEnter selection (c, d, w, or q): ");
               
      }
      updateServiceCharge(&balance, &serviceCharge, &cheques, &bounced, &deposits, &withdrawals);
      getchar();
      getchar();
      return 0;
    }
    void updateServiceCharge(double *p_balance, double *p_serviceCharge, int *p_cheques, int *p_bounced, int *p_deposits, int *p_withdrawals)
    {
      *p_serviceCharge = (*p_cheques)*1.5+(*p_bounced)*15.0+(*p_deposits)*0.5+(*p_withdrawals)*0.5;
      *p_balance = *p_balance - *p_serviceCharge;
      printf("\n");
      printf("Transaction       Debit       Credit         Balance\n");
      printf("****************************************************\n");
      printf("Cheque            %.2lf                       %.2lf\n", *p_serviceCharge, *p_balance);
      printf("****************************************************\n\n");  
    }
    void updateWithdrawal(double *p_balance, double *p_withdrawal, int *p_withdrawals)
    {
      printf("Enter amount of withdrawal: ");
      scanf("%lf", p_withdrawal);
      if(*p_withdrawal <= *p_balance && *p_withdrawal>=0){
        *p_balance = *p_balance - *p_withdrawal;
        *p_withdrawals = *p_withdrawals + 1;
        printf("\n");
        printf("Transaction       Debit       Credit         Balance\n");
        printf("****************************************************\n");
        printf("Cheque            %.2lf                       %.2lf\n", *p_withdrawal, *p_balance);
        printf("****************************************************\n\n");
      }
      else{
        printf("Invalid amount!\n");
        updateWithdrawal(p_balance, p_withdrawal, p_withdrawals);
      }
    }
    void updateDeposit(double *p_balance, double *p_deposit, int *p_deposits)
    {
        printf("Enter amount of deposit: ");
        scanf("%lf", p_deposit);
      if(*p_deposit>=0){
        *p_balance = *p_balance + *p_deposit;
        *p_deposits = *p_deposits + 1;
        printf("\n");
        printf("Transaction       Debit       Credit         Balance\n");
        printf("****************************************************\n");
        printf("Cheque                        %.2lf           %.2lf\n", *p_deposit, *p_balance);
        printf("****************************************************\n\n");
      }
      else{
        printf("Invalid amount!\n");
        updateDeposit(p_balance, p_deposit, p_deposits);
      }
    }
    void updateCheque(double *p_balance, double *p_cheque, int *p_cheques, int *p_bounced)
    {
      printf("Enter amount of cheque: ");
      scanf("%lf", p_cheque);
      if(*p_cheque<=*p_balance && *p_cheque>0){
        *p_balance = *p_balance - *p_cheque;
        *p_cheques = *p_cheques + 1;
        printf("\n");
        printf("Transaction       Debit       Credit         Balance\n");
        printf("****************************************************\n");
        printf("Cheque            %.2lf                        %.2lf\n", *p_cheque, *p_balance);
        printf("****************************************************\n\n");
      }
      else if(*p_cheque>*p_balance){
        printf("The amount is greater than balance!\n");
        *p_bounced = *p_bounced + 1;
      }
      else{
        printf("Invalid input!\n");
        updateCheque(p_balance, p_cheque, p_cheques, p_bounced);
      }
    }
    
    void getBalance(double *p_balance)
    {
      printf("Welcome to the Cheque Book Balancer\n\n");
      printf("Please enter the current balance: ");
      scanf("%lf", p_balance);
      printf("\n");
      printf("*******************************************************\n");
      printf("Balance forward                                  %.2lf\n", *p_balance);
      printf("*******************************************************\n\n");
    }
    
    char getTrans()
    {
      char ch;
      scanf("%c", &ch);
      return ch;
    }
    
    void transMenu()
    {
      printf("Transaction Menu\n");
      printf("================\n");
      printf("c - Cheque\n");
      printf("d - Deposit\n");
      printf("w - Withdrawal\n");
      printf("q - Quit\n");
      printf("================\n");
      printf("Enter selection (c, d, w, or q): ");
    }

  9. #9
    Registered User cbastard's Avatar
    Join Date
    Jul 2005
    Location
    India
    Posts
    167
    Code:
    char getTrans()
    {
      char ch;
      scanf("%c", &ch);
      return ch;
    }
    ch is an auto variable.this type of variable are out of scope after the function gettrans finishes.You are returning the value(ch) which does'nt exist anymore.
    Long time no C. I need to learn the language again.
    Help a man when he is in trouble and he will remember you when he is in trouble again.
    You learn in life when you lose.
    Complex problems have simple, easy to understand wrong answers.
    "A ship in the harbour is safe, but that's not what ships are built
    for"

  10. #10
    & the hat of GPL slaying Thantos's Avatar
    Join Date
    Sep 2001
    Posts
    5,681
    Quote Originally Posted by cbastard
    Code:
    char getTrans()
    {
      char ch;
      scanf("%c", &ch);
      return ch;
    }
    ch is an auto variable.this type of variable are out of scope after the function gettrans finishes.You are returning the value(ch) which does'nt exist anymore.
    That function is perfectly valid. It is returning a non-address value so there is no problem with it. If it had been returning a pointer to char and returning the address of ch then there would be a problem.

  11. #11
    Registered User
    Join Date
    Nov 2005
    Posts
    13
    Ok, but what is the problem with while loop?

  12. #12
    ZuK
    ZuK is offline
    Registered User
    Join Date
    Aug 2005
    Location
    Austria
    Posts
    1,990
    try this
    Code:
    #include <stdio.h>
    char getTrans(){
      char ch;
      scanf("%c", &ch);
      return ch;
    }
    int main() {
       char trans;
       double balance;
       while ( (trans = getTrans() ) != 'q' ) {
          printf( "0x%02x\n", trans );
        }
       return 0;
    }
    that should show you what's wrong with your loop.
    Kurt

  13. #13
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,046
    What's balance for?
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  14. #14
    ZuK
    ZuK is offline
    Registered User
    Join Date
    Aug 2005
    Location
    Austria
    Posts
    1,990
    True that's useless.
    Kurt

  15. #15
    Registered User
    Join Date
    Nov 2005
    Posts
    13
    Quote Originally Posted by ZuK
    try this that should show you what's wrong with your loop.
    Ok, it gives me some kind of references or something to characters I enter. How is that suppose to show me what's wrong with the loop?

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. problem with functions
    By saliya in forum C Programming
    Replies: 1
    Last Post: 11-05-2007, 09:36 PM
  2. Problem with system(), execl(), etc. functions
    By nickkrym in forum C Programming
    Replies: 5
    Last Post: 05-12-2007, 08:04 AM
  3. Problem with pointers and functions
    By Kheila in forum C++ Programming
    Replies: 5
    Last Post: 10-13-2005, 12:40 PM
  4. Problem with functions
    By lizardking3 in forum C++ Programming
    Replies: 4
    Last Post: 09-22-2003, 04:34 PM
  5. problem with functions and "parse errors"
    By bart in forum C++ Programming
    Replies: 3
    Last Post: 08-27-2001, 08:52 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21