home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #31 / NN_1992_31.iso / spool / comp / lang / cplus / 18597 < prev    next >
Encoding:
Text File  |  1992-12-31  |  1.8 KB  |  60 lines

  1. Newsgroups: comp.lang.c++
  2. Path: sparky!uunet!taumet!steve
  3. From: steve@taumet.com (Steve Clamage)
  4. Subject: Re: Simulate "Pointer to char" by an array
  5. Message-ID: <1992Dec31.170449.24707@taumet.com>
  6. Organization: TauMetric Corporation
  7. References: <1992Dec30.172241.11378@dcs.warwick.ac.uk>
  8. Date: Thu, 31 Dec 1992 17:04:49 GMT
  9. Lines: 49
  10.  
  11. cmchan@dcs.warwick.ac.uk (C M Chan) writes:
  12.  
  13.  
  14. >How can I simulate "pointer to char" by an array in a class whose size will be
  15. >delayed to be defined at run time?
  16. >For example,
  17. >     class X {
  18. >     private:
  19. >             char string[      ];    /* not define size of the array */
  20. >                              ^^^^^^^^
  21. >     public:
  22. >             ...............
  23. >     };
  24.  
  25. You cannot have an incomplete type as the member of a class (or struct,
  26. even in C).  You may be thinking of this C trick:
  27.     struct foo {
  28.         ...
  29.         char string[1]; /* last member of struct */
  30.     };
  31.     ...
  32.     struct foo *fp = malloc(sizeof(foo) - 1 + SIZE);
  33. You then treat fp->string as if it had SIZE elements.  It is probably
  34. not legal in C, but it seems to work on most if not all implementations.
  35.  
  36. Do NOT do this with a C++ class!
  37.  
  38. This trick breaks the type system, and you are lying to the compiler
  39. about the type of such objects and pointers.  The exact composition
  40. of a class is wired into a lot of C++, and you may find bizarre
  41. program behavior.
  42.  
  43. If you want to defer choosing the size of the array until run time,
  44. make "string" a pointer and allocate the space with "new":
  45.  
  46.     class X {
  47.         char *string;
  48.     public:
  49.         X(size_t size) { string = new char [size]; }
  50.         ~X()           { delete [] string; }
  51.     };
  52.  
  53. Although this seems to add another indirection to string access, I
  54. think you will find in practice that the difference is negligible.
  55. -- 
  56.  
  57. Steve Clamage, TauMetric Corp, steve@taumet.com
  58.