为什么不能在C ++中返回正确的动态大小数组?

时间:2016-03-20 10:45:00

标签: c++

我的问题:

当我在下面的代码中返回指针float data时,我遇到了一些问题。

如何在1 4CodeA中打印相同的输出CodeB

说明

CodeA中,data已声明为n * n浮点数组。并由一些值分配。

然后打印它们将获得正确的值。

CodeB中,arr是浮点指针。它是函数get2dArrayData的返回数组。

然后打印它们将得到不正确的值。 (好像溢出?)

CodeA:输出为' 1 4'

float * Application::get2dArrayData(int n) {
  float data[n * n];

  ... // Assign something (data[0] = 1, data[1] = 4, ...) here.

  // Print data here.
  cout << data[0] << "  " << data[1] << endl;

  return data;
}

CodeB:输出类似于&#39; 2.8026e-45 6.03325e-34&#39;

void Application::main() {
  float * arr = this->get2dArrayData(5);

  // Print data here.
  // But got error memory address.
  cout << arr[0] << " " << arr[1] << endl;

  return;
}

我尝试在static中为data添加CodeA

static float data[n * n];

将显示此错误消息。

error: variable length array declaration cannot have 'static' storage duration
       static float data[n * n];
                         ^^^^^

0 个答案:

没有答案