How to create a dynamic array of integers

How to create a dynamic array of integers in C++ using the new keyword?

498571 次浏览

使用 new动态分配一些内存:

int* array = new int[SIZE];
int main()
{
int size;


std::cin >> size;


int *array = new int[size];


delete [] array;


return 0;
}

Don't forget to delete every array you allocate with new.

int* array = new int[size];

你也许该考虑用标准模板库。它简单易用,而且不用担心内存分配。

Http://www.cplusplus.com/reference/stl/vector/vector/

int size = 5;                    // declare the size of the vector
vector<int> myvector(size, 0);   // create a vector to hold "size" int's
// all initialized to zero
myvector[0] = 1234;              // assign values like a c++ array

由于 C + + 11,有一个安全的替代 new[]delete[],这是零开销不同于 std::vector:

std::unique_ptr<int[]> array(new int[size]);

In C++14:

auto array = std::make_unique<int[]>(size);

上述两种方法都依赖于同一个头文件 #include <memory>

一旦有关动态数组的问题出现,您可能不仅希望创建具有可变大小的数组,还希望在运行时更改其大小。这里有一个 memcpy的例子,你也可以使用 memcpy_s或者 std::copy。根据编译器的不同,可能需要 <memory.h><string.h>。使用此函数时,分配新的内存区域,将原始内存区域的值复制到该内存区域,然后释放它们。

//    create desired array dynamically
size_t length;
length = 100; //for example
int *array = new int[length];


//   now let's change is's size - e.g. add 50 new elements
size_t added = 50;
int *added_array = new int[added];


/*
somehow set values to given arrays
*/


//    add elements to array
int* temp = new int[length + added];
memcpy(temp, array, length * sizeof(int));
memcpy(temp + length, added_array, added * sizeof(int));
delete[] array;
array = temp;

You may use constant 4 instead of sizeof(int).

#include <stdio.h>
#include <cstring>
#include <iostream>


using namespace std;


int main()
{


float arr[2095879];
long k,i;
char ch[100];
k=0;


do{
cin>>ch;
arr[k]=atof(ch);
k++;
}while(ch[0]=='0');


cout<<"Array output"<<endl;
for(i=0;i<k;i++){
cout<<arr[i]<<endl;
}


return 0;
}

上面的代码可以工作,可以定义的最大 float 或 int 数组大小为2095879,退出条件是开始输入号不为零

The answers above are all good for assigning one-dimensional int-arrays. Anyhow, I want to add that it is also possible to do this for multi-dimensional arrays you'd normally define like int[][] matrix = \{\{1,2}, {3,4}}.

关键是将所有元素存储在一个数组中,并利用这个数组是内存中的一个连续块的事实(请参阅 给你以了解“块”的说明) ,这意味着您可以通过维度“分割”自己。下面你可以看到一个2d 数组的例子。

你可以在 SO 上找到关于这个主题 给你的讨论。

/*Defining a 2d-matrix.*/
struct Matrix {


int rows, columns;
int* matrix;


Matrix(int rows, int columns) : rows(rows), columns(columns) {
// This approach uses a single array since "new" cannot create
// multidimensional arrays.
// It also spares the performance cost of an array of arrays.
matrix = new int[columns * rows];
}


~Matrix() {
// Release the memory after destroying the Matrix-object
delete[] matrix;
}


/*Access the element at position [r]ow and [c]olumn.*/
int getElement(int r, int c) {
// matrix[c][r] is rewritten as matrix[column + columns * rows]
// -> matrix <=> Single memory block
return matrix[c + columns * r];
}


/*Set the element at position [r]ow and [c]olumn with given [val]ue.*/
void setElement(int r, int c, int val) {
matrix[c + columns * r] = val;
}
};

填充这样一个 Matrix对象的示例是:

    /*Initialize the matrix with the continuous numbers 0..N*/
void Matrix::initDummyMatrix(){
int counter = 0;
for (int row = 0; row < rows; ++row) {
for (int col = 0; col < columns; ++col) {
setElement(row, col, counter++);
}
}
}