An array inside of struct, without knowing the size?

hello, so today i came across this little problem. Im trying to make an array inside of struct, its all fine, but the thing is that i dont know the size of that array yet. How do i set the size during the runtime?

-Thank you!!!:)

example:

1
2
3
4
5
6
7
8
9
10
struct pav
{
    int something[];
};

int main()
{
    pav structoreOfPav;
    structoreOfPav.something[13] = 10;
}
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
struct pav
{
    int* something;
};

int main()
{
    pav structoreOfPav;

    int whatever = whatever;

    structoreOfPav.something = new int[whatever];

    structoreOfPav.something[13] = 10;
}


it means you make something a pointer to int, and you call new memory with whatever size you need.

AeonFlux1212
Last edited on
Solution: don't use arrays or pointers, use a container type like std::vector.
1
2
3
4
struct pav
{
    std::vector<int> something;
};
http://www.cplusplus.com/reference/vector/vector/
http://en.cppreference.com/w/cpp/container/vector
AeonFlux1212, yeah, i've tried pointers before and didnt have much luck with them.. Thank you so much. You healed my headache mate.. :D
-Thanks!
I strongly recommend not using pointers in this case ;)
@LB

why is that?
Last edited on
@matkenis

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
struct pav
{
    int* something;
};

int main()
{
    pav structoreOfPav;

    int whatever = whatever;

    structoreOfPav.something = new int[whatever];

    structoreOfPav.something[13] = 10;

    delete[] structoreOfPay.something;
}


don't forget to delete heap or stack (is that heap or stack?) memory when you don't need it anymore.

AeonFlux1212
Last edited on
@AeonFlux1212
@LB

Im confused. Both ways worked, wich is better and why? :d
-Thanks for the help guys!:)
With pointers, you have to manually manage ownership of the allocated data and make sure that delete[] is called exactly once when you are done with it. There are many obscure ways to get it wrong and it is really difficult even for professional programmers to get it right in all cases.

With containers like std::vector all the hard work is done for you and you even get a nice interface as a bonus.
@LB thanks a lot for the help!:)
Last edited on
Topic archived. No new replies allowed.