Can I create a structure with non-constant array lengths_

Can I create a structure with an array, in which different instances of the structure have differing lengths for the array?

Pseudo-code example:
1
2
3
4
5
6
7
8
9
struct mystruct {
int myarray [varlength]
}

mystruct struct1:
int struct1.myarray [10];

mystruct struct2:
int struct2.myarray [20];

Can I achieve this functionality with deques and arrays maybe?
Last edited on
http://www.cplusplus.com/doc/tutorial/dynamic/
You may also want to read the previous chapter on pointers. ;)
I read both of those yesterday and I think I understand them, so I know that I can easily create an array on the heap, and that array can have a size depending on some variable "size" int that I have specified, by using something like mypoint * int = new int [length].

But that would create an array that is not inside a structure instance. How do I create an array of length int length inside an instance of a structure when the structure was defined before I had that variable, and considering that each instance of my structure will have a different length. Is this possible with arrays or will I need to use vectors?
Have the array structure contain an int*, and new it when you whenever you like.
1
2
3
4
5
6
struct a {
    int* b;
} s1, s2;

s1.b = new int[length];
s2.b = new int[different_length];
Last edited on
If I do that, when I do a delete on s1, will it remove the array b as well?
No, it won't. Mainly because you'll get a compile error (you can't delete something you didn't make with new!), but if you did dynamically allocate s1, then it still wouldn't - it'd delete s1, which deletes the pointer named b, but it wouldn't delete the memory that b points to.

You could write a destructor, just put this inside your struct:
1
2
3
4
5
6
7
~a() //destructor for the a struct/class
{
  if(b != NULL)
  {
    delete b;
  }
}


Of course, this is moving more and more toward object oriented programming, in which the class/struct manages itself. Just remember that a struct and a class are exactly the same, except that structs have an invisible public: at the start, and classes have an invisible private: at the start. Choose one for typing convenience. ;)
Last edited on
Topic archived. No new replies allowed.