簡體   English   中英

為什么我的陣列顯示不加起來?

[英]Why does my array display does not add up?

顯示時名為“stop”的變量不會相加。 它應該顯示“輸入數組 1 然后 2...5 的數字”。

#include <stdlib.h>
#include <stdio.h>
#include <stddef.h>

#define MAX_SIZE 1000 

void main(){
    int num[MAX_SIZE];
    printf("Input number of integers in the array: ");
    scanf("%d", &num[MAX_SIZE]);
    
    for(size_t stop=0; stop<num[MAX_SIZE]; stop++){
        printf("\nInput numbers for array %d: ", num[stop]);
        scanf("%d", &num[stop]);
        

    }
}

圖片

你有兩個選擇。

  1. 保留預處理器指令:
#include <stdlib.h>
#include <stdio.h>

#define MAX_SIZE 10 

int main(){
    int num[MAX_SIZE];
    int i;
    
    for(i=0; i < MAX_SIZE; i++){
        printf("\nInput numbers for array %d: ", i);
        scanf("%d", &num[i]);
    }
    return 0;
}
  1. 或者,這很可能是您想要做的,使用動態內存分配:
#include <stdlib.h>
#include <stdio.h>

int main(){
    int *num;
    int i, MAX_SIZE;

    printf("Input number of integers in the array: ");
    scanf("%d", &MAX_SIZE);

    num = (int *)malloc(MAX_SIZE * sizeof(int)); // allocate dynamic memory
    
    for (i=0; i < MAX_SIZE; i++){
        printf("\nInput numbers for array %d: ", i);
        scanf("%d", &num[i]);
    }

    free(num); // free pointer
    return 0;
}

暫無
暫無

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

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