Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!think.com!samsung!uunet!taumet!steve From: steve@taumet.com (Stephen Clamage) Newsgroups: comp.lang.c++ Subject: Re: structures with variable length elements. Message-ID: <736@taumet.com> Date: 20 May 91 17:23:36 GMT References: <1991May18.010928.16619@cshl.org> Organization: Taumetric Corporation, San Diego Lines: 37 monardo@cshl.org (Pat Monardo) writes: >i am only superficially aware of C++, so.... >i recall that PL1 would allow a structure to contain variable length >elements (depending on a length parameter). With C i would >have to declare a pointer and allocate the memory. >Did PL1 allocate the vector inline? Does C++ do this? There is a "trick" in C to make variable-length structures: struct phony { ... int i[1]; /* must be last field in the struct */ }; Then you create an instance like phony *p = (phony*)malloc(sizeof(phony) + 511*sizeof(int)); getting a version of a phony with an array of 512 ints at element 'i'. This is very poor programming practice, in my view. Another way, which also works in C++, is to make 'i' a pointer, then allocate an array for 'i' to point to whenever you create an instance of the struct. Then the order of the fields doesn't matter. In C, this technique requires some careful bookkeeping, but in C++ it all goes in the constructor and destructor, and you don't have to worry about it in the rest of the code. class var_int { ... int *ip; int array_size; // size of the ip array public: var_int(int sz); // constructor allocates array of sz ints ~var_int(); // destructor deallocates the array size(); // return number of elements int& operator[](int index); // access array element }; -- Steve Clamage, TauMetric Corp, steve@taumet.com