Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/155.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 我的数组代码有什么问题_C++_Arrays - Fatal编程技术网

C++ 我的数组代码有什么问题

C++ 我的数组代码有什么问题,c++,arrays,C++,Arrays,我试图生成一个数组,它可能与维度无关。我试过这么做 #include <iostream> using namespace std; class array3d { public: array3d(size_t* d, int dims) { int all = 1; size_t* dimensions; int* array; for (size_t i = 0; i < dims; i++) { all =

我试图生成一个数组,它可能与维度无关。我试过这么做

#include <iostream>

using namespace std;

class array3d
{
public:    
  array3d(size_t* d, int dims)
  {
    int all = 1;
    size_t* dimensions;
    int* array;

    for (size_t i = 0; i < dims; i++) {
      all = d[i];
      dimensions = new size_t[dims];
      array = new int[all];
      std::cout << array[i] << std::endl;
    }
  }
};

int main()
{
  size_t d[6];
  d[0] = 2;
  d[1] = 3;
  d[2] = 4;
  d[3] = 2;
  d[4] = 3;
  d[5] = 4;
  array3d arr(d, 6);
  return 0;
}

当我编译它时,我只得到一个零数组,我无法找到哪里出错了。有人能帮忙吗?

我不能真正理解代码背后的逻辑,但如果您只是想看到打印出来的内容,您可能打算这样做:

array = new int [all];
//write something here first!
array[i] = some_value; <--- Note that this may access past the end of the array
std::cout << array[i] << std::endl;
或者更可能是您想要:

std::cout << d[i] << std::endl;
注1:除非您真的需要数组,否则您应该真正地听0d0a并使用std::vector

注2:您正在进行一些有符号到无符号的比较iarray=new int[all];不初始化分配的内存。它只是从堆中进行分配,但保留内存内容不变,或者,严格来说,访问已分配但未初始化的内存可能是未定义的行为

您只是偶然看到零,因为内存恰好包含零。它是零可能是因为您的程序尚未分配、使用和发布它,而操作系统在将它提供给您的程序之前将其填充为零


另外,std::cout Google:如何使用调试器。对于动态数组,您应该使用std::vector。您打印数组[i],但从不在数组中放入任何内容。您希望发生什么?