【问题标题】:How to point to an array pointer (array [x]) in c如何在c中指向数组指针(数组[x])
【发布时间】:2015-11-23 21:37:54
【问题描述】:

我刚刚完成了一个我一直在研究的程序并且它运行正常,但我想通过消除重复代码来改进它。所以我想我可以通过指向数组指针本身来做到这一点,但我不太确定如何做到这一点。我的教授没有详细说明这一点。

我在想,如果我用类似于balance [x] = deposit_choice - 1 的方式更改balance [0-4] 的出现,我会在消除重复代码方面走上正轨,但没有任何效果符合我的预期。我尝试创建两个不同的功能;一个用于更改balance [x] 的值,另一个用于运行算法,但我有点不知道该怎么做。

由于它们运行得不是很好,所以算法的第一次迭代没有改变:

case 3:
          show_account_menu(balance, 5);
          printf("An account balance of -1.00 means your account has not been opened yet.\n\n");
          printf("\nWhat account would you like to deposit in?\n" );// inputprompt
          scanf(" %d", &deposit_choice);
          if ((deposit_choice > 5) || (account_choice <1)){ //can only deposit in accounts 1-5
            printf("\n***  Invalid account selection!!  ***\n");
          }

            // start of account 1
            if(deposit_choice == 1){
              if(balance [0] == -1.00 ){
                printf("You have not created an account yet.\n");
                break;

              }else if (balance [0] >= 0.00){
                  printf("Enter an amount to deposit: ");//input
                  scanf("%d", &deposit);
                  printf("\n-------------------------------\n");
                    if(deposit >= 0){
                      printf("\n* Your new balance is: %.2f *\n\n",balance[0]=balance[0]+deposit);
                      break;
                    }else{
                      printf("Invalid input!\n\n");//deposit validation
                      break;
                    }
                  }

                //start of account 2
              }else if(deposit_choice == 2){

如果有人可以帮助我,我将不胜感激。我觉得如果我能理解如何解决这个问题,我将能够巩固如何使用指针、数组甚至函数。

如果你想在这里查看整个代码:

      #include <stdio.h>

    void show_bank_menu(void){
      printf("\n**-**-**-**-**-**-**-**-Welcome to Scrubs Bank-**-**-**-**-**-**-**-**-\n");
      printf("**-**-**-**-**-**-**-**How may I help you today**-**-**-**-**-**-**-**-\n");
      printf("********************~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~********************\n");
      printf("**********$$$$$$****~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~******$$$$$$$*******\n");
      printf("********$$$$$$$$$***  1. View Accounts...          *****$$$$$$$$$******\n");    /*introduction*/
      printf("********$$$$**$$$$**  2. Open Accounts...          ****$$$$**$$$$******\n");
      printf("********$$$$********  3. Deposit...                **********$$$$******\n");
      printf("***$$$$**$$$********  4. Withdraw...               **********$$$***$$$*\n");
      printf("***$$$$$$$$$********  5. Exit                      **********$$$$$$$$**\n");
      printf("****$$$$$$$*********~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~***********$$$$$$***\n");
      printf("********************~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~********************\n");
      printf("**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**\n");
      printf("**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**\n");
    }

    void show_account_menu(float array[ ], int size ){
      int x;
      for( x = 0 ; x < size ; x++ ) {
        printf("%d: %.2f\n", x+1, array[x]);
      }
    }



    int main (void) {
      int choice, account_choice, deposit_choice, withdraw_choice;
      float balance [5]= {-1.00,-1.00,-1.00,-1.00,-1.00};
      int deposit=0;
      int withdraw=0;

        //bank menu selection
        show_bank_menu();
        printf("\nchoice: ");
        scanf("%d", &choice);

        while (choice !=5){
          switch(choice){
            case 1:
    //show account
            show_account_menu(balance,5);
            printf("An account balance of -1.00 means your account has not been opened yet.\n\n");
              break;

              case 2:
              show_account_menu(balance,5);
              printf("An account balance of -1.00 means your account has not been opened yet.\n\n");
                printf("Which account would you like to open?\n" );
                scanf("%d", &account_choice );
                if ((account_choice > 5) || (account_choice <1)){
                  printf("\n***  Invalid account selection!!  ***\n");
                }
    //open account
                  if(account_choice == 1){
                    printf("\n");
                    balance [0]=0.00;
                    show_account_menu(balance,5);
                  }else if(account_choice == 2){
                    printf("\n");
                    balance [1]=0.00;
                    show_account_menu(balance,5);
                  }else if(account_choice == 3){
                    printf("\n");
                    balance [2]=0.00;
                    show_account_menu(balance,5);
                  }else if(account_choice == 4){
                    printf("\n");
                    balance [3]=0.00;
                    show_account_menu(balance,5);
                  }else if(account_choice == 5){
                    printf("\n");
                    balance [4]=0.00;
                    show_account_menu(balance,5);
                  }
                  break;
    //deposit
                  case 3:
                  show_account_menu(balance, 5);
                  printf("An account balance of -1.00 means your account has not been opened yet.\n\n");
                  printf("\nWhat account would you like to deposit in?\n" );// inputprompt
                  scanf(" %d", &deposit_choice);
                  if ((deposit_choice > 5) || (account_choice <1)){
                    printf("\n***  Invalid account selection!!  ***\n");
                  }

                    // start of account 1
                    if(deposit_choice == 1){
                      if(balance [0] == -1.00 ){
                        printf("You have not created an account yet.\n");
                        break;

                      }else if (balance [0] >= 0.00){
                          printf("Enter an amount to deposit: ");//input
                          scanf("%d", &deposit);
                          printf("\n-------------------------------\n");
                            if(deposit >= 0){
                              printf("\n* Your new balance is: %.2f *\n\n",balance[0]=balance[0]+deposit);
                              break;
                            }else{
                              printf("Invalid input!\n\n");//deposit validation
                              break;
                            }
                          }

                        //start of account 2
                      }else if(deposit_choice == 2){
                        if (balance [1] == -1.00){
                          printf("You have not created an account yet.\n" );
                          break;

                        }else if(balance [1] >= 0.00){
                        printf("Enter an amount to deposit: ");
                        scanf("%d", &deposit);//input
                        printf("\n-------------------------------\n");
                          if(deposit >= 0){
                            printf("\n* Your new balance is: %.2f *\n\n",balance[1]=balance[1]+deposit);
                            break;
                          }else{            //validation
                            printf("Invalid input!\n\n");
                            break;
                          }
                        }


                      }else if(deposit_choice == 3){//start account 3
                        if(balance [2] == -1.00){
                          printf("You have not created an account yet.\n");
                          break;

                        }else if(balance [2] >= 0.00){
                        printf("Enter an amount to deposit: ");
                        scanf("%d", &deposit);                      //input
                        printf("\n-------------------------------\n");
                          if(deposit >= 0){
                            printf("\n* Your new balance is: %.2f *\n\n",balance[2]=balance[2]+deposit);
                            break;
                          }else{
                            printf("Invalid input!\n\n");//validation
                            break;
                          }
                        }

                      }else if(deposit_choice == 4){
                        if (balance [3] == -1.00){
                          printf("You have not created an account yet.\n" );
                          break;

                        }else if(balance [3] >= 0.00){
                        printf("Enter an amount to deposit: ");
                        scanf("%d", &deposit);//input
                        printf("\n-------------------------------\n");
                          if(deposit >= 0){
                            printf("\n* Your new balance is: %.2f *\n\n",balance[3]=balance[3]+deposit);
                            break;
                          }else{            //validation
                            printf("Invalid input!\n\n");
                            break;
                          }
                        }


                      }else if(deposit_choice == 5){// start account 5
                        if (balance [4] == -1.00){
                          printf("You have not opened the account yet.\n");
                          break;

                        }else if(balance [4] >= 0.00){
                        printf("Enter an amount to deposit: ");
                        scanf("%d", &deposit);                  //input
                        printf("\n-------------------------------\n");
                          if(deposit >= 0){
                            printf("\n* Your new balance is: %.2f *\n\n",balance[4]=balance[4]+deposit);
                            break;
                          }else{
                            printf("Invalid input!\n\n");    //validation
                            break;
                           }
                         }
                       }
    //end of withdraw options
                    break;
    //withdraw
                    case 4:
                    show_account_menu(balance, 5);
                    printf("An account balance of -1.00 means your account has not been opened yet.\n\n");
                    printf("\nWhat account would you like to withdraw out of?\n" );// inputprompt
                    scanf(" %d", &withdraw_choice);
                    if ((withdraw_choice > 5) || (account_choice <1)){
                      printf("\n***  Invalid account selection!!  ***\n");
                    }

                      // start of account 1
                      if(withdraw_choice == 1){
                        if(balance [0] == -1.00 ){
                          printf("You have not created an account yet.\n");
                          break;

                        }else if (balance [0] >= 0.00){
                            printf("Enter an amount to withdraw: ");//input
                            scanf("%d", &withdraw);
                            printf("\n-------------------------------\n");
                              if(withdraw > balance [0] ){
                                printf("\nInsufficient funds!\n");
                                break;
                              }else if(withdraw >= 0){
                                printf("\n* Your new balance is: %.2f *\n\n",balance[0]=balance[0]-withdraw);
                                break;
                              }else{
                                printf("Invalid input!\n\n");//deposit validation
                                break;
                              }
                            }

                          //start of account 2
                        }else if(withdraw_choice == 2){
                          if (balance [1] == -1.00){
                            printf("You have not created an account yet.\n" );
                            break;

                          }else if(balance [1] >= 0.00){
                            printf("Enter an amount to withdraw: ");
                            scanf("%d", &withdraw);//input
                            printf("\n-------------------------------\n");
                              if( withdraw > balance [1] ){
                                printf("Insufficient funds!\n");
                                break;
                              }else if(withdraw >= 0){
                                printf("\n* Your new balance is: %.2f *\n\n",balance[1]=balance[1]-withdraw);
                                break;
                              }else{            //validation
                                printf("Invalid input!\n\n");
                                break;
                              }
                            }

                          //start of account 3
                        }else if(withdraw_choice == 3){
                          if (balance [2] == -1.00){
                          printf("You have not created an account yet.\n");
                          break;

                          }else if(balance [2] >= 0.00){
                            printf("Enter an amount to withdraw: ");
                            scanf("%d", &withdraw);//input
                            printf("\n-------------------------------\n");
                              if(withdraw > balance [2] ){
                                printf("Insufficient funds!\n");
                                break;
                              }else if(withdraw >= 0){
                                printf("\n* Your new balance is: %.2f *\n\n",balance[2]=balance[2]-withdraw);
                                break;
                              }else{            //validation
                                printf("Invalid input!\n\n");
                                break;
                            }
                          }
                        //start of account 4
                      }else if(withdraw_choice == 4){
                        if (balance [3] == -1.00){
                        printf("You have not created an account yet.\n");
                        break;

                        }else if(balance [3] >= 0.00){
                          printf("Enter an amount to withdraw: ");
                          scanf("%d", &withdraw);//input
                          printf("\n-------------------------------\n");
                          if(withdraw > balance [3] ){
                            printf("Insufficient funds!\n");
                          }else if(withdraw >= 0){
                              printf("\n* Your new balance is: %.2f *\n\n",balance[3]=balance[3]-withdraw);
                              break;
                            }else{            //validation
                              printf("Invalid input!\n\n");
                              break;
                            }
                          }
                        //start of account 5
                      }else if(withdraw_choice == 5){
                        if (balance [4] == -1.00){
                        printf("You have not created an account yet.\n");
                        break;

                        }else if(balance [4] >= 0.00){
                          printf("Enter an amount to withdraw: ");
                          scanf("%d", &withdraw);//input
                          printf("\n-------------------------------\n");
                            if(withdraw > balance [4] ){
                              printf("Insufficient funds!\n");
                            }else if(withdraw >= 0){
                                printf("\n* Your new balance is: %.2f *\n\n",balance[4]=balance[4]-withdraw);
                                break;
                            }else{            //validation
                              printf("Invalid input!\n\n");
                              break;
                            }
                          }
                        }


                  /*open accounts*/
                        break;

                          case 5:
                            printf("\nGood day!\n");
                          return 0;


                    default:
                    printf("-----------------------");
                    printf("\n Not an option!\n");
                    printf("-----------------------\n");

        }// end switch

        show_bank_menu();

        printf("choice: ");
        scanf("%d", &choice);
        printf("\n");




      }//end while

      return 0;
    }//end main

【问题讨论】:

  • 您能否也添加您尝试删除重复但不起作用的代码?
  • 看起来你所追求的是balance[deposit_choice - 1]。请务必首先验证 deposit_choice 是否在 1 - 5 范围内,并确保在块中的任何位置进行替换。这样您就不需要为每个帐户重复相同的代码了。
  • 哇,谢谢大家!我不敢相信它那么容易,我想我简直不敢相信它那么容易!我还修复了缩进的格式。

标签: c arrays function pointers


【解决方案1】:

这就是你要找的吗?请注意,balance[0] 的实例已替换为 balance[deposit_choice - 1]

          if(balance [deposit_choice - 1] == -1.00 ){
              printf("You have not created an account yet.\n");
              break;

          }else if (balance [deposit_choice - 1] >= 0.00){
              printf("Enter an amount to deposit: ");//input
              scanf("%d", &deposit);
              printf("\n-------------------------------\n");
              if(deposit >= 0){
                printf("\n* Your new balance is: %.2f *\n\n",balance[deposit_choice - 1] = balance[deposit_choice - 1] + deposit);
                break;
              }else{
                printf("Invalid input!\n\n");//deposit validation
                break;
              }
          }

附:你的缩进很奇怪。您应该确保您的缩进量始终相同,此外,为块的 INSIDE 添加缩进(即我注意到您缩进了if 语句,但缩进应该从后面的行开始)。

【讨论】:

  • 对于老年人来说,1-2 个字符的缩进不足以使块易于区分。标准的每级 4 个字符是好的——即使对于体弱者也是如此。
【解决方案2】:

欢迎来到 C :-) 这是一个不错的入门程序,您减少通用代码的直觉会很好地为您服务。

我建议使用您的帐户 ID 作为余额中的索引,而不是硬连接您的索引。 我认为这就是您在原始问题中的目标,您非常接近。 下面将“修改”版本与“原始”版本进行比较。 输入帐户 ID 的验证逻辑很好。 验证帐户后(例如 1 - 5 ),您可以减去一个并直接索引您的余额数组。

您还可以做一些其他事情来整合您的代码。 如果他们还没有从函数返回值(例如,到目前为止只有 void fncts),那么这可能是一个暂时停止的好地方。 例如,您的菜单函数实际上可以返回选项,并且您将合并相当数量的 scanf() 和其他输入验证。

* 修改 * 注意:我实际上并没有尝试编译此代码以确保它有效,但我希望这个想法很清楚。

case 3:
show_account_menu(balance, 5);
printf("An account balance of -1.00 means your account has not been opened yet.\n\n");
printf("\nWhat account would you like to deposit in?\n" );// inputprompt
scanf(" %d", &deposit_choice);
if ((deposit_choice > 5) || (account_choice <1)){
  printf("\n***  Invalid account selection!!  ***\n");
}
// NEW - this was the tricky part.
deposit_choice = deposit_choice - 1;

// delete // start of account 1
// delete if(deposit_choice == 1){
// dont need to do this, we know deposit_choice is smth from 0 thru 4 (e.g. acct#'s 1 thru 5).
// === start of deposit for *all* accounts ===
   // NEW - use deposit_choice to indicate which balance they wanted to work with.
   if(balance [deposit_choice] == -1.00 ) {
      printf("You have not created an account yet.\n");
      break;
   } else if (balance [deposit_choice] >= 0.00) {
      printf("Enter an amount to deposit: ");//input
      scanf("%d", &deposit);
      printf("\n-------------------------------\n");
      if(deposit >= 0){
         //original: printf("\n* Your new balance is: %.2f *\n\n",balance[0]=balance[0]+deposit);
         //style note: easier to read if you keep assignment logic outside of printing.
         //note how we modify balance, then print out the new one.
         balance[deposit_choice] = balance[deposit_choice] + deposit;
         printf("\n* Your new balance is: %.2f *\n\n",balance[deposit_choice] );
         break;
      }else{
         printf("Invalid input!\n\n");//deposit validation
         break;
      }
   }
// delete: //start of account 2
// delete: } else if(deposit_choice == 2) {
// delete:      if (balance [1] == -1.00){
// delete:        printf("You have not created an account yet.\n" );
// delete:        break;
// delete: ...etc. for accounts 3, 4 & 5 deposit handling.

原文:来自长列表...

case 3:
show_account_menu(balance, 5);
printf("An account balance of -1.00 means your account has not been opened yet.\n\n");
printf("\nWhat account would you like to deposit in?\n" );// inputprompt
scanf(" %d", &deposit_choice);
if ((deposit_choice > 5) || (account_choice <1)){
  printf("\n***  Invalid account selection!!  ***\n");
}

// start of account 1
if(deposit_choice == 1){
   if(balance [0] == -1.00 ) {
      printf("You have not created an account yet.\n");
      break;
   } else if (balance [0] >= 0.00) {
      printf("Enter an amount to deposit: ");//input
      scanf("%d", &deposit);
      printf("\n-------------------------------\n");
      if(deposit >= 0){
      printf("\n* Your new balance is: %.2f *\n\n",balance[0]=balance[0]+deposit);
      break;
      }else{
      printf("Invalid input!\n\n");//deposit validation
      break;
      }
   }
//start of account 2
} else if(deposit_choice == 2) {
   if (balance [1] == -1.00) {
      printf("You have not created an account yet.\n" );
      break;

补充说明:数组本质上只是一个指针,带有方括号的索引表示法便于让编译器找出要使用的内存中的实际偏移量(例如,双精度数往往比字符长,所以mychars[5] 与 mydoubles[5] 的实际字节偏移量会有所不同(前者实际上可能只是从 mychars 开始向下 5 个字节,而后者可能是 5*8=40 字节向下,或者但是在你的特定 cpu + 编译器上有很多字节长的双精度)。我知道这些天很酷的孩子会谈论 size_t 等等。只是为了好玩,请尝试以下操作:

printf( "char: %d\n",   sizeof(char) );
printf( "short: %d\n",  sizeof(short) );
printf( "int: %d\n",    sizeof(int) );
printf( "long: %d\n",   sizeof(long) );
printf( "float: %d\n",  sizeof(float) );
printf( "double: %d\n", sizeof(double) );

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-25
    • 2010-10-25
    • 1970-01-01
    • 1970-01-01
    • 2021-01-26
    相关资源
    最近更新 更多