【发布时间】:2019-12-24 13:55:17
【问题描述】:
我无法解决问题。该程序必须根据用户的需要增加数组的大小。但是,它会跳过条件并开始显示数组本身。
int main() {
int *ptr;
int limit;
int sum = 0;
int ans;
printf("enter the limit of the array\n");
scanf_s("%d", &limit);
ptr = (int *)malloc(limit * sizeof(int));
for (int i = 0; i < limit; i++) {
printf("enter element %d : ", i + 1);
scanf_s("%d", (ptr + i));
if (i = limit) {
printf("do you want to stop entering?\n");
printf("\t\t1\t0\n");
if (scanf_s("%d", &ans) == '1') {
break;
} else
if (scanf_s("%d", &ans) == '0') {
limit += 5;
ptr = (int *)realloc(ptr, limit * sizeof(int));
printf("memory re-allocation is completed succesfully!\n");
}
}
}
for (int i = 0; i < limit; i++) {
printf("\nthis is your %d. element : %d\n", i + 1, *(ptr + i));
}
return EXIT_SUCCESS;
}
【问题讨论】:
-
if (i = limit)==>if (i == limit)...哦! 并打开警告和注意警告! -
scanf_s的返回值是整数,因此不会等于字符值'1'或'0'。需要使用ans获取用户输入的值。 -
请注意,
realloc()可能会失败,它通过返回空指针来表示。您的程序在实践中不太可能在条目数量适中的情况下遇到这种情况,但精心设计的代码会检查此类错误并在发生时适当地处理这种情况。 -
如果您使用
gcc,您可以使用-Wall -Werror进行编译以启用警告。 -
请注意,如果重新分配失败,
ptr = (int*)realloc(ptr, limit * sizeof(int));会泄漏内存。始终使用void *new_ptr = realloc(old_ptr, new_size); if (new_ptr == NULL) { …deal with failed reallocation… } old_ptr = new_ptr; old_size = new_size;或等效项(您可能会记录一些项目而不是字节大小;这很好)。