【问题标题】:Array size allocation at compile time, expecting constant value [duplicate]编译时的数组大小分配,期望恒定值[重复]
【发布时间】:2014-08-23 06:09:46
【问题描述】:
// testing1.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <vector>
#include <iostream>
#include<conio.h>

using namespace std;


struct Data_point {
  double  x;
  double  y;
};


    void PlotThis(unsigned int n ) 
{
    Data_point graph[n];  //shows error here 

    //do something else, dont worry about that  
}


int main ()

{

unsigned int nSamples;  
cout << "Please enter nSamples: ";
cin >> nSamples;
PlotThis(nSamples);
return 0; 

}

编译时显示错误:

Error   1   error C2057: expected constant expression testing1.cpp  23

Error   2   error C2466: cannot allocate an array of constant size 0 testing1.cpp   23

Error   3   error C2133: 'graph' : unknown size  testing1.cpp   23

第23行是Data_point graph[n]; //这里显示错误

即使我将 main() 中的值传递给它,它仍显示未知大小。它在编译时要求值(图的大小,即 n)。这是否意味着数组大小分配发生在编译时?如何解决这个问题

【问题讨论】:

  • 在 ubuntu 12 上使用 g++ 4.6.3 编译时没有错误
  • @Vink,使用 -pedantic 编译(或 -pedantic-errors 以实际匹配您的声明)。
  • 相关问题提供了更多关于此处被视为常量的详细信息:Does “int size = 10;” yield a constant expression?

标签: c++


【解决方案1】:

C++ 不支持在运行时确定大小的数组。您可以改用 Vector 类。

std::vector<Data_point > graph;

按照您使用的逻辑:在PlotThis 中,您可以使用std::vector::resize 调整容器的大小以包含n 元素。

void PlotThis(unsigned int n){
    graph.resize(n); // Resize Vector container
    ...

还有std::vector:

"compared to arrays, vectors consume more memory in exchange for 
 the ability to manage storage and grow dynamically in an efficient way."

这意味着您可以选择不用担心指定vector 的大小,而只需根据需要添加元素。所以你可以有一个循环来确定在你的方法中添加了多少元素(n)——可以使用std::vector::push_back。如果您这样做,那么只需确保在某个时候清除 vector,这样您就不会重复使用旧数据 - 可以使用 std::vector::clear

【讨论】:

  • 但是如何传递向量长度?
  • graph.resize(n)。请注意,在 c++11 之前,std::vector&lt;&gt;.resize() 通过复制构造来初始化新元素。
【解决方案2】:

你可以使用一些容器,例如vector、deque等...

void PlotThis(unsigned int n) 
{
    std::vector<Data_point> graph(n);

    //do something else, dont worry about that  
}

或者为数组动态分配内存:

//C++
void PlotThis(unsigned int n) 
{
    Data_point* graph = new Data_point[n];

    //do something else, dont worry about that  

    //Remember to free memory
    delete graph;
}


//C
void plot_this(unsigned int n) 
{
    Data_point* graph = (Data_point*) malloc(sizeof(Data_point) * n);

    //do something else, dont worry about that  

    //Remember to free memory
    free(graph);
}

【讨论】:

    猜你喜欢
    • 2014-08-18
    • 2014-09-11
    • 1970-01-01
    • 2016-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-28
    • 1970-01-01
    相关资源
    最近更新 更多