Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Chương trình C++ triển khai mảng chiều dài biến đổi


Mảng chiều dài biến đổi (Variable length arrays) có kích thước theo yêu cầu người dùng, tức kích thước có thể thay đổi.

Chương trình triển khai mảng chiều dài biến đổi trong C++:

Ví dụ

#include <iostream> #include <string> using namespace std; int main() {    int *array, size;    cout<<"Enter size of array: "<<endl;    cin>>size;    array = new int [size];    cout<<"Enter array elements: "<<endl;    for (int i = 0; i < size; i++)    cin>>array[i];    cout<<"The array elements are: ";    for(int i = 0; i < size; i++)    cout<<array[i]<<" ";    cout<<endl;    delete []array;    return 0; }

Kết quả chương trình:

Enter size of array: 10 Enter array elements: 11 54 7 87 90 2 56 12 36 80 The array elements are: 11 54 7 87 90 2 56 12 36 80

Trong chương trình, mảng được khởi tạo. Sau đó nhập kích thước và phần tử:

cout<<"Enter size of array: "<<endl; cin>>size; array = new int [size]; cout<<"Enter array elements: "<<endl; for (int i = 0; i < size; i++) cin>>array[i];

Cuối cùng hiển thị phần tử và xóa mảng:

cout<<"The array elements are: "; for(int i = 0; i < size; i++) cout<<array[i]<<" "; cout<<endl; delete []array;