动态分配多维数组的方法 [英] A way of allocating multidimensional arrays dynamically

查看:166
本文介绍了动态分配多维数组的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

致敬..



我在一本书中学习多维数组的动态分配,我找到了一些方法,现在没有问题了。
但是这本书的作者向我们展示了一种方法,但它不能正常工作。这是:

  pbeans = new double [3] [4]; //为3x4数组分配内存

这是错误:

 错误C2440:'=':无法从'int(*)[4]'转换为'int *'



我应该如何定义 pbeans (如果这种类型的编码合法)?


解决方案 / div>

这在我的阵列常见问题中列出:

  double(* pbeans)[4]; 
pbeans = new double [3] [4];

// ...

delete [] pbeans;

对于C declarator impaired,你可以使用typedef更容易阅读:

  typedef double row [4]; 

row * pbeans;
pbeans = new row [3];

// ...

delete [] pbeans;

但是在C ++中,我们更喜欢用裸指针的RAII容器:

  #include< vector> 
#include< array>

std :: vector< std :: array< double,4> >豆类(3);

注意完全没有 delete [] 这使得此解决方案是异常安全的。


salute..

I am learning dynamic allocations for multidimensional arrays in a book and I found some ways for that, And now haven't problem in it. But the author of the book shows us a way, but it doesn't work correctly. It is this:

pbeans = new double [3][4];         // Allocate memory for a 3x4 array

And this is the error:

error C2440: '=' : cannot convert from 'int (*)[4]' to 'int *'

how should i define pbeans ( if this type of coding is legal)?

and what is the problem exactly?

Regards.

解决方案

This is covered in my FAQ on arrays:

double (*pbeans)[4];
pbeans = new double[3][4];

// ...

delete[] pbeans;

For the "C declarator impaired", you could make that more readable with a typedef:

typedef double row[4];

row *pbeans;
pbeans = new row[3];

// ...

delete[] pbeans;

But in C++, we prefer RAII containers over raw pointers:

#include <vector>
#include <array>

std::vector<std::array<double, 4> > beans(3);

Note the complete absence of delete[] which makes this solution exception-safe.

这篇关于动态分配多维数组的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆