C语言函数中数组元素存入数组的问题求助
嘿,我来帮你拆解下代码里的问题,还有怎么把这个存款功能弄对~
你的代码核心问题分析
1. 函数调用的参数错误
在main里调用choiceG时,你写了choiceG (&array[DEPOSIT]);,这里有两个致命问题:
array[DEPOSIT]是数组的第6个元素(数组下标从0开始,DEPOSIT是5),这属于越界访问,会触发未定义行为(程序可能崩溃或输出乱码)。- 你要传递的是主函数里的整个数组,但这里传的是单个越界元素的地址,而且类型完全不匹配:
choiceG的参数定义是unsigned *array[DEPOSIT](这是一个存放unsigned指针的数组),但你实际需要传递的是int数组的指针,两者根本不兼容。
2. choiceG函数的逻辑偏差
这个函数的设计完全偏离了你的需求:
- 你在函数内部定义了局部数组
int a[5] = { 0 };,把用户输入的存款存在这个局部数组里。但局部数组在函数执行结束后会被系统销毁,主函数里的array根本拿不到这些数据,等于白存了。 - 函数参数的定义错误,你不需要接收指针数组,只需要接收主函数里int数组的指针(等价于
int array[])。 - 最后打印的时候,你用
printf("%p ", (void *) &a[j]);打印的是数组元素的内存地址,而不是用户输入的存款数值,应该直接打印元素值。
3. 输入缓冲区的小坑
scanf("%c", &choice);会读取输入缓冲区里的换行符,导致下次循环时直接触发default选项(因为上次输入后的换行符留在了缓冲区)。可以改成scanf(" %c", &choice);(%c前加空格,自动跳过空白字符)。
修正后的代码示例
我把核心问题都修复了,你可以参考这个版本继续开发:
#include <stdio.h> #include <stdlib.h> #include <ctype.h> #define DEPOSIT 5 // 修改参数:接收int数组的指针(等价于int array[]) void choiceG(int array[DEPOSIT]); int main() { char choice; int sum, maxim, minim, aver = 0; int array[DEPOSIT] = {0}; // 初始化数组为0,避免垃圾值 do { printf("\nChoose an option from the menu below:\n"); printf("\tG\t-\tGet a new deposit\n"); printf("\tS\t-\tSum of all deposits\n"); printf("\tD\t-\tDeposits to be displayed from highest to lowest\n"); printf("\tA\t-\tAverage of all deposits\n"); printf("\tL\t-\tLowest deposit will be displayed\n"); printf("\tQ\t-\tQuit the program\n"); printf("\nYour choice (please use uppercase): "); scanf(" %c", &choice); // 加空格跳过换行符,避免误判 switch (choice) { case 'G': choiceG(array); // 直接传数组名,数组名会自动退化为指针 break; case 'S': printf("Sum function to be implemented\n"); break; case 'D': printf("Sort display function to be implemented\n"); break; case 'A': printf("Average function to be implemented\n"); break; case 'L': printf("Lowest deposit function to be implemented\n"); break; case 'Q': printf("Quitting program...\n"); break; default: printf("Incorrect menu option selected.\n"); } } while (choice != 'Q'); return 0; } // 直接操作主函数传过来的数组,数据会保留到主函数中 void choiceG(int array[DEPOSIT]) { int i; printf("Please enter %d deposit amounts:\n", DEPOSIT); for(i = 0; i < DEPOSIT; ++i ){ printf("Deposit # %d - $", i+1); // 从1开始显示更符合用户习惯 scanf("%d", &array[i]); // 直接把输入存到主函数的数组里 } printf("Your deposit amounts are: $ "); for(i = 0; i < DEPOSIT ; i++){ printf("%d ", array[i]); // 打印存款数值,不是地址 } printf("\n"); }
额外的改进建议
- 增加输入验证:存款金额不能是负数,可以在
scanf之后判断,如果输入值小于0,提示用户重新输入。 - 支持小写选项:可以把输入的
choice转成大写再判断,比如choice = toupper(choice);,这样用户输入小写也能正常识别。 - 增加状态标记:比如定义一个
int has_deposits = 0;,用户选G后设为1,后面选S/A/L时先判断这个标记,避免用户还没输入存款就计算出错误结果。
内容的提问来源于stack exchange,提问作者iAm Bob
相关产品推荐
相关产品推荐

