home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c++
- Path: sparky!uunet!taumet!steve
- From: steve@taumet.com (Steve Clamage)
- Subject: Re: Simulate "Pointer to char" by an array
- Message-ID: <1992Dec31.170449.24707@taumet.com>
- Organization: TauMetric Corporation
- References: <1992Dec30.172241.11378@dcs.warwick.ac.uk>
- Date: Thu, 31 Dec 1992 17:04:49 GMT
- Lines: 49
-
- cmchan@dcs.warwick.ac.uk (C M Chan) writes:
-
-
- >How can I simulate "pointer to char" by an array in a class whose size will be
- >delayed to be defined at run time?
- >
- >For example,
- >
- > class X {
- > private:
- > char string[ ]; /* not define size of the array */
- > ^^^^^^^^
- > public:
- > ...............
- > };
-
- You cannot have an incomplete type as the member of a class (or struct,
- even in C). You may be thinking of this C trick:
- struct foo {
- ...
- char string[1]; /* last member of struct */
- };
- ...
- struct foo *fp = malloc(sizeof(foo) - 1 + SIZE);
- You then treat fp->string as if it had SIZE elements. It is probably
- not legal in C, but it seems to work on most if not all implementations.
-
- Do NOT do this with a C++ class!
-
- This trick breaks the type system, and you are lying to the compiler
- about the type of such objects and pointers. The exact composition
- of a class is wired into a lot of C++, and you may find bizarre
- program behavior.
-
- If you want to defer choosing the size of the array until run time,
- make "string" a pointer and allocate the space with "new":
-
- class X {
- char *string;
- public:
- X(size_t size) { string = new char [size]; }
- ~X() { delete [] string; }
- };
-
- Although this seems to add another indirection to string access, I
- think you will find in practice that the difference is negligible.
- --
-
- Steve Clamage, TauMetric Corp, steve@taumet.com
-