我写了一段代码,它必须确定数组在范围[X,Y]中最大的负元素并删除它。之后,没有该元素的数组的“更新”版本显示在屏幕上。数组元素的数量,数组元素的值,X和Y值由用户输入。
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n, i, X, Y;
printf("Type in the number of array elements: ");
scanf("%d", &n);
if (n <= 0) {
printf("The number of array elements must be a positive value. \n");
return 1;
}
/* Dynamic memory allocation */
int* arr = (int*)malloc(n * sizeof(int));
/* Checking in if the dynamic memory allocation went successfully */
if (arr == NULL) {
printf("A dynamic memory allocation went unsuccessfully. \n");
return 1;
}
printf("Type in the array elements' values. \n");
for (i = 0; i < n; ++i) {
printf("%d element: ", i + 1);
scanf("%d", &arr[i]);
}
do {
printf("Type in space-separated X and Y values (x < 0): ");
scanf("%d %d", &X, &Y);
if (X >= 0) {
printf("X must be a negative value. \n");
}
} while (X >= 0);
int last_negative = 1;
int maxx = arr[0];
for (i = 0; i < n; ++i) {
if (arr[i] >= X && arr[i] <= Y && arr[i] < 0) {
last_negative = 0;
if (arr[i] > maxx) {
maxx = arr[i];
}
}
}
if (last_negative == 1) {
printf("There are no array elements in range [%d, %d].\n", X, Y);
free(arr); /* Freeing the allocated memory */
return 1;
}
/* Deleting the largest negative element that we founded */
for (i = maxx; i < n - 1; ++i) {
arr[i] = arr[i + 1];
}
/* Reducing the array length by one */
arr = (int*)realloc(arr, (n - 1) * sizeof(int));
printf("The largest negative element in range [%d, %d] was deleted.\n The final outcome: \n", X, Y);
for (i = 0; i < n - 1; ++i) {
printf("%d ", arr[i]);
}
/* Freeing the allocated memory */
free(arr);
return 0;
}
字符串
我是C编程的新手,所以我可能不太明白一些事情。我知道我的代码有问题,但我真的不能说到底是什么问题。希望得到一些帮助:(
2条答案
按热度按时间nzkunb0c1#
你很可能正在经历一个无限循环或一个非常慢的循环。
i = maxx
是错误的,因为i
是数组索引,而maxx
是值。要修复它,您可能需要添加新的数组索引变量maxi
,并执行maxi = i;
,以及稍后的i = maxi;
。为了进一步调试,添加许多
printf
(在每一个代码行之间),并查看每一个被打印了多少次。x4shl7ld2#
你的代码中似乎有一些问题。我做了一些修改来解决这些问题:
字符串
*动态内存分配:
malloc
来创建一个整数数组。但是,如果发生错误或程序正常退出,它不会释放此内存。这可能导致内存泄漏。*删除最大负元素的循环条件:
for (i = maxx; i < n - 1; ++i)
,但它应该是for (i = 0; i < n; ++i)
,因为您希望遍历整个数组以查找并删除最大负元素。*内存分配:
realloc
重新分配内存。然而,这是在没有检查realloc
操作是否成功的情况下完成的。如果重新分配失败,程序可能会遇到问题。*查找最大负元素的循环条件:
arr[0]
替换maxx
,然后从开始迭代以查找最大负元素。这是可以的,但代码可以从索引1开始循环,因为maxx
已经用arr[0]
初始化。*删除最大负数元素:
arr[i] = arr[i + 1];
删除最大的负数元素。但是,它没有正确处理最后一个元素。它应该在删除元素后将数组长度减少1,并且不尝试访问现在越界的元素。*打印最终结果的循环条件:
for (i = 0; i < n - 1; ++i)
。但是,由于删除最大的负元素后数组长度减少了1,因此应该是for (i = 0; i < n - 1; ++i)
。*消息小改进:
我的响应中修改的代码解决了这些问题,它释放了动态分配的内存,纠正了循环条件,并增加了对内存操作成功的检查。