An array inside of struct, without knowing the size?

Oct 9, 2015 at 6:40pm
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 Oct 9, 2015 at 6:41pm
Oct 9, 2015 at 6:53pm
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 Oct 9, 2015 at 6:56pm
Oct 9, 2015 at 7:03pm
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
Oct 9, 2015 at 7:03pm
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!
Oct 9, 2015 at 7:04pm
I strongly recommend not using pointers in this case ;)
Oct 9, 2015 at 8:06pm
@LB

why is that?
Last edited on Oct 9, 2015 at 8:17pm
Oct 9, 2015 at 8:16pm
@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 Oct 9, 2015 at 8:17pm
Oct 9, 2015 at 9:19pm
@AeonFlux1212
@LB

Im confused. Both ways worked, wich is better and why? :d
-Thanks for the help guys!:)
Oct 10, 2015 at 10:53am
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.
Oct 10, 2015 at 3:23pm
@LB thanks a lot for the help!:)
Last edited on Oct 10, 2015 at 3:24pm
Topic archived. No new replies allowed.