I have some problem with my code. I wanna using struct array to calculate something.

But my array size is dynamic not static.

Here's my code

#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;
    }
}

As you can see the num_max is dynamic, it will change value according user input what value on it.

So my question is:

How to let MAX get the same value with num_max

I know that that is not possible so must use others ways, such as

2 Answers

3
lubgr On

How to let MAX get the same value with num_max?

That's impossible. MAX is a compile-time constant (that you would better declare as e.g. constexpr std::size_t max = 5; instead of using the preprocessor), while num_max is a value determined at runtime.

The difference with respect to array sizes is that you must dynamically allocate the memory for arrays with a runtime-dependent size. As suggested in the comments, you typically don't do that manually, but instead rely on an existing type, often a template.

Example for your case:

#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});

Note that passing the default Point instance {0, 0} to std::vector::resize is optional here, as the function will value-initialize the newly created elements, which is is zero-initialization in this case.

1
Community On

There are some ways here.

  • In C++

    You can use 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;
    }
    
  • In C(since C99)

    You can use VLA(Variable-length array)

    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;
    }
    
  • In C(before C99)

    You can allocate the memory dynamically

    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;
    }