2017-08-03 44 views
-1

我輸入應該是這樣的:什麼是最好的方式來存儲N量的數組? ç

n array1 array2 array3 array4 ... arrayn 

其中n爲整數,數組1 .. arrayn是數組。數組總是有4個元素。 我可以做這樣的事情:

int n,array[100][4]; 
for(int i=0;i<=n-1;i++) 
{ 
    for(int j=0;j<=3;j++) 
    { 
     scanf("%d",&array[i][j]); 
    } 

} 

但是,這是一個矩陣,我覺得有更好的解決方案,但我真的想不出任何...

+6

有什麼不對的矩陣? – Barmar

+1

_注意:_你不想'scanf(「%d」,&array [i] [j]);'? –

+1

@Barmar我需要儘可能地學會節省空間/記憶......我只是在尋找其他的選擇,而我的大腦拒絕提出不同的東西。 – Dafuq

回答

2

什麼是最好的方式存儲N個數組的數組?
陣列總是有4個元素

一些選擇:什麼是最好的取決於未說明的編碼目標。如果不確定,請考慮選項B。每個使用大約相同數量的內存。 VLA住在本地,應該避免大n

unsigned n = rand(); 

    // arrayA as array n of array 4 of int 
    // Variable-Length-Array (VLA) available in C99 and optionally in C11 
    // UB if n == 0 
    int arrayA[n][4]; 
    arrayA[0][0] = 42; 
    // no free() needed. Become invalid at the end of the block 

    // arrayB as pointer to array 4 of int 
    // Allocate memory for a n 1D arrays 
    int (*arrayB)[4] = malloc(sizeof *arrayB * n); 
    if (n > 0) arrayB[0][0] = 42; 
    free(arrayB); // Valid until free'd 

    // arrayC as pointer to array n of array 4 of int 
    // Allocate memory for a 2D VLA (C99,C11 maybe) 
    // UB if n == 0 
    int (*arrayC)[n][4] = malloc(sizeof *arrayC); 
    (*arrayC)[0][0] = 42; 
    free(arrayC); // Valid until free'd 

malloc()返回值應檢查NULL-ness

p = malloc(sizeof *p * n); 
    if (p == NULL && n > 0) { 
    Handle_OutOfMemory(); 
    } 
相關問題