1. 程式人生 > >使用指標來實現變長陣列(VLA)

使用指標來實現變長陣列(VLA)

實現程式碼:

#include <cstdio>
#include <cstdlib>
void usePtoImplementVLA(int SIZE)
{
    scanf("%d", &SIZE);
    int *pVLA = (int *)malloc(sizeof(int) * SIZE);
    
    for (int i = 0; i < SIZE; i++)
        scanf("%d", &pVLA[i]);
    
    free(pVLA);
}

實現思路:

1、輸入建立指標大小SIZE
2、使用sizeof

函式得出需要的空間大小。例:輸入10sizeof(int) * SIZE得出40。
3、使用malloc函式動態分配記憶體空間。(注:一般的時候,malloc函式與free函式連用)
4、用for迴圈輸入每一個數據。
5、用free函式釋放記憶體空間。

參考資料:

cplusplus-malloc
百度百科-malloc
cppreference-sizeof