簡體   English   中英

通過超出數組的限制重新分配數組的大小

[英]Reallocating the size of the array by exceeding the limit of it

我無法解決問題。 該程序必須根據用戶的意願增加數組的大小。 但是,它會跳過條件並開始顯示數組本身。

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語句:

if (i = limit)

不比較ilimit 相反,它將limit的值分配給i然后它檢查此表達式的結果是否為非零。 如果是,則進入該塊,否則將被跳過。

=是賦值運算符。 使用相等運算符==比較兩個操作數。

if (i == limit)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM