如何在 C 中创建动态整数数组?

发布于 2024-09-28 20:54:13 字数 48 浏览 3 评论 0原文

如何使用 new 关键字在 C++ 中创建动态整数数组?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

把回忆走一遍 2024-10-05 20:54:13
int main()
{
  int size;

  std::cin >> size;

  int *array = new int[size];

  delete [] array;

  return 0;
}

不要忘记删除使用new分配的每个数组。

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.

脱离于你 2024-10-05 20:54:13

从 C++11 开始,有一个安全的替代方案来替代 new[]delete[] ,与 std::vector 不同,它是零开销的:

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

在 C++14 中:

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

以上两者都依赖于相同的头文件,#include

Since C++11, there's a safe alternative to new[] and delete[] which is zero-overhead unlike std::vector:

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

In C++14:

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

Both of the above rely on the same header file, #include <memory>

慕巷 2024-10-05 20:54:13

您可能需要考虑使用标准模板库。它简单易用,而且您不必担心内存分配。

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

You might want to consider using the Standard Template Library . It's simple and easy to use, plus you don't have to worry about memory allocations.

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
記憶穿過時間隧道 2024-10-05 20:54:13
int* array = new int[size];
int* array = new int[size];
じ违心 2024-10-05 20:54:13

一旦问题涉及动态数组,您可能不仅想要创建具有可变大小的数组,而且还想要在运行时更改其大小。这是一个使用 memcpy 的示例,您也可以使用 memcpy_sstd::copy 。根据编译器的不同,可能需要 。使用此函数时,您分配新的内存区域,将原始内存区域的值复制到其中,然后释放它们。

//    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;

您可以使用常量 4 代替 sizeof(int)

As soon as question is about dynamic array you may want not just to create array with variable size, but also to change it's size during runtime. Here is an example with memcpy, you can use memcpy_s or std::copy as well. Depending on compiler, <memory.h> or <string.h> may be required. When using this functions you allocate new memory region, copy values of original memory regions to it and then release them.

//    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).

彼岸花似海 2024-10-05 20:54:13

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

int* array = new int[SIZE];

dynamically allocate some memory using new:

int* array = new int[SIZE];
寄与心 2024-10-05 20:54:13

上面的答案都适合分配一维 int 数组。无论如何,我想补充一点,对于通常定义的多维数组也可以执行此操作,如 int[][] matrix = {{1,2}, {3,4}}.

关键是将所有元素存储在一个数组中,并利用数组是内存中的连续块这一事实(请参阅此处< /a> 来澄清“块”),这意味着你可以通过维度“切片”自己。下面您可以看到二维数组的示例。

您可以在此处<找到有关此主题的讨论< /a> 就这样。

/*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;
    }
};

填充此类矩阵对象的示例如下:

    /*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++);
            }
        }
    }

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}}.

The key is that you store all elements in one array and make use of the fact that the array is a continuous block in memory (see here for a clarification of "block"), meaning that you can "slice" yourself through dimensions. Below you can see an example for a 2d-array.

You can find a discussion regarding this topic here on 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;
    }
};

An example to populate such a Matrix-object would be:

    /*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++);
            }
        }
    }
寂寞美少年 2024-10-05 20:54:13
#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,退出条件将为非零开始输入数字

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

The above code works, the maximum float or int array size that could be defined was with size 2095879, and exit condition would be non zero beginning input number

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文