C语言数组校验问题:判断数组元素是否全相同的代码报错求助
数组元素校验失败的问题排查与修复
你的代码存在几个关键错误,导致即使输入相同元素也会判断错误,逐一说明并修复:
错误点分析
- 数组未正确填充:输入循环中仅读取了数值到
num变量,却没有将数值存入数组arr的对应位置,数组始终是未初始化的垃圾值,无法正确校验。 - 校验函数数组越界:
check函数的循环条件i < dim会导致当i = dim-1时,访问arr[i+1]即arr[dim],超出数组有效下标范围(0~dim-1),触发未定义行为。 - 无效冗余代码:
arr[dim];这条语句没有任何实际功能,属于无效代码,可直接删除。 - 输出文本拼写错误:输出中的
he elements缺少首字母T,应改为The elements。
修正后的完整代码
#include <stdio.h> #include <stdbool.h> #define MAX_DIM 30 int check(int[], int); int main(int argc, char *argv[]) { int dim; int arr[MAX_DIM]; printf("Insert an array dimension. \n"); printf("Remember that the maximum size the array can take is %d \n\n", MAX_DIM); printf("Array dimension: "); scanf("%d", &dim); if (dim > MAX_DIM || dim <= 0) { // 新增维度合法性校验,排除非正整数 printf("Array dimension isn't valid! \n"); return 0; } printf("\n"); printf("Enter the numbers to place in the array of size %d \n", dim); for (int i = 0; i < dim; i++) { scanf("%d", &arr[i]); // 直接读取到数组对应位置,无需中间变量 } int equals = check(arr, dim); if (equals == 1) { printf("The elements of the array are all the same \n"); } else { printf("The elements of the array are not all the same \n"); } } int check(int arr[], int dim) { // 处理数组为空或只有一个元素的情况,直接返回全部相同 if (dim <= 1) { return 1; } for (int i = 0; i < dim - 1; i++) { // 循环到dim-2即可,避免越界 if (arr[i] != arr[i + 1]) { return -1; } } return 1; }
额外补充:新增了维度非正整数的合法性校验,同时简化了输入逻辑,还处理了数组维度为0或1的边界情况,让代码更健壮。
内容的提问来源于stack exchange,提问作者user13716820
相关产品推荐
相关产品推荐

