Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

โปรแกรม C++ สำหรับการนำอาร์เรย์ความยาวแปรผัน (Variable Length Array) ไปใช้งาน


อาร์เรย์ความยาวแปรผัน (Variable Length Arrays) สามารถมีขนาดตามที่ผู้ใช้ต้องการ กล่าวคือ สามารถมีขนาดที่เปลี่ยนแปลงได้

โปรแกรม C++ สำหรับการนำอาร์เรย์ความยาวแปรผันไปใช้งาน มีดังนี้:

ตัวอย่าง

#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; 
}

ผลลัพธ์ของโปรแกรมข้างต้นจะเป็นดังนี้:

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

ในโปรแกรมนี้ เริ่มต้นด้วยการเริ่มต้นอาร์เรย์ จากนั้นขอขนาดอาร์เรย์และองค์ประกอบจากผู้ใช้ โค้ดส่วนนี้มีดังนี้:

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;