2017-04-01 13 views
1

我有一个设置元素1 - 10的数组。我已经决定了数组的大小,我决定了数组的元素。我的问题是,如何创建一个大小为x的数组,并用元素1,2,3,4填充它。 。 。如何更改数组的大小并使用自动化元素填充它?

//sets values of the array elements and print them. 
cout << "Array should contain x integers set to 1,2,3" << endl; 

// QUESTION: How can I change the size of the array and have 
//   have values automatically entered? 
int array[] = { 1,2,3,4,5,6,7,8,9,10 }; 
for (int i = 0; i <= (sizeof(array)/sizeof(int)-1); ++i) { 

    // sizeof(array)/sizeof(int) = 36/4. ints are 4. 
    cout << "Element " << i << " = " << array[i] << endl; 
} 
    cout << "The number of elements in the array is: " 
    << sizeof(array)/sizeof(int) << endl; 
    cout << endl; 
    cout << endl; 
+0

你需要一个动态数组,对吧?我认为这个http://stackoverflow.com/questions/4029870/how-to-create-a-dynamic-array-of-integers是有用的。 –

+0

'int array [x]; std :: iota(std :: begin(array),std :: end(array),1);' –

+0

编译时是否已知数组的大小? – zett42

回答

1

你可以对你的数组使用动态内存分配方法,在那里你可以给你想要的大小。谢谢。

//Variable size of Array program to print Array elements 

#include <iostream> 
using namespace std; 

int main() 
{ 
    cout << "Enter Array size x:" << endl; 
    int x = 0; 
    cin >> x; 

    int *ptrArray = new int[x]; 

    //Inittialise Array 
    for (int i = 0; i < x; i++) 
    { 
     ptrArray[i] = i + 1; 
    } 

    //Print Array elemts 
    cout << "Array elements:"; 
    for (int i = 0; i < x; i++) 
    { 
     cout << ptrArray[i] << endl; 
    } 

    delete[] ptrArray; 

    return 0; 
} 
+0

太棒了!谢谢! –

相关问题