【问题标题】:Reallocating the size of the array by exceeding the limit of it通过超出数组的限制来重新分配数组的大小
【发布时间】: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; 或等效项(您可能会记录一些项目而不是字节大小;这很好)。

标签: c arrays malloc realloc


【解决方案1】:

代码中的if 语句:

if (i = limit)

不比较 ilimit。相反,它将limit 的值分配给i,然后检查此表达式的结果是否非零。如果是则进入该块,否则跳过。

= 是赋值运算符。使用相等运算符== 比较两个操作数。

if (i == limit)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-03
    • 2018-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多