如何在“ #define”上定义动态值

时间:2019-03-25 08:32:04

标签: c++

我的代码有问题。 我想使用结构数组来计算某些东西。

但是我的数组大小不是动态的。动态

这是我的代码

#include <iostream>
#define MAX 5
using namespace std;
struct Point{
    int x,y;
}arrayy[MAX];

int main(){
    int num_howmanytime,num_max;
    cin >> num_howmanytime;
    while(num_howmanytime--){
    cin >> num_max;
    }
}

如您所见, num_max 是动态的,它将根据用户输入更改值。

所以我的问题是:

如何让 MAX num_max

获得相同的值

我知道这是不可能的,因此必须使用其他方式,例如

2 个答案:

答案 0 :(得分:3)

  

如何让MAX与num_max获得相同的值?

那是不可能的。 MAX是一个编译时常量(最好将其声明为constexpr std::size_t max = 5;而不是使用预处理器),而num_max是在运行时确定的值。

关于数组大小的区别在于,您必须为与运行时相关的大小的数组动态分配内存。如评论中所建议,您通常不手动执行此操作,而是依赖现有类型(通常是模板)。

您的案例示例:

#include <vector>

std::vector<Point> points;

cin >> num_max;

// Set the runtime array size, let the vector allocate its memory.
// Also, provide a default initial value for all Point instances.
points.resize(num_max, {0, 0});

请注意,将默认Point实例{0, 0}传递给std::vector::resize是可选的,因为该函数将对新创建的元素进行值初始化,在这种情况下为零初始化。

答案 1 :(得分:1)

这里有一些方法。

  • 在C ++中

    您可以使用std::vector

    struct Point {
        int x, y;
    };
    
    int main() {
        int num_howmanytime, num_max;
        cin >> num_howmanytime;
        while (num_howmanytime--) {
            cin >> num_max;
            std::vector<Point> arrayy(num_max);
        }
        return 0;
    }
    
  • 在C中(自C99起)

    您可以使用VLA(可变长度数组)

    struct Point {
        int x, y;
    };
    
    int main() {
        int num_howmanytime, num_max;
        scanf("%d", &num_howmanytime);
        while (num_howmanytime--) {
            scanf("%d", &num_max);
            struct Point arrayy[num_max];
        }
        return 0;
    }
    
  • 在C中(在C99之前)

    您可以动态分配内存

    struct Point {
        int x, y;
    };
    
    int main() {
        int num_howmanytime, num_max;
        scanf("%d", &num_howmanytime);
        while (num_howmanytime--) {
            scanf("%d", &num_max);
            struct Point *arrayy;
            arrayy = malloc(sizeof(struct Point) * num_max);
        }
        return 0;
    }
    
相关问题