Try to be a little less terse about dealing with variable-length structs
authorTom Lane
Wed, 14 Nov 2001 22:14:22 +0000 (22:14 +0000)
committerTom Lane
Wed, 14 Nov 2001 22:14:22 +0000 (22:14 +0000)
in C, but recommend that newbies who don't recognize this trick should do
some studying ...

doc/src/sgml/xfunc.sgml

index 59dcea3551063847397f27367499d3e8a575c688..fed2036236b9afc39f2a72686fc13095fab72469 100644 (file)
@@ -1,5 +1,5 @@
 
 
  
@@ -947,11 +947,18 @@ typedef struct {
     
 
     
-     Obviously,  the  data  field shown here is not long enough to hold
-     all possible strings; it's impossible to declare such
-     a  structure  in  C.  When manipulating 
+     Obviously,  the  data  field declared here is not long enough to hold
+     all possible strings.  Since it's impossible to declare a variable-size
+     structure in C, we rely on the knowledge that the
+     C compiler won't range-check array subscripts.  We
+     just allocate the necessary amount of space and then access the array as
+     if it were declared the right length.  (If this isn't a familiar trick to
+     you, you may wish to spend some time with an introductory
+     C programming textbook before delving deeper into
+     Postgres server programming.)
+     When manipulating 
      variable-length types, we must  be  careful  to  allocate  
-     the  correct amount  of memory and initialize the length field.  
+     the  correct amount  of memory and set the length field correctly.
      For example, if we wanted to  store  40  bytes  in  a  text
      structure, we might use a code fragment like this:
 
@@ -962,9 +969,13 @@ char buffer[40]; /* our source data */
 ...
 text *destination = (text *) palloc(VARHDRSZ + 40);
 destination->length = VARHDRSZ + 40;
-memmove(destination->data, buffer, 40);
+memcpy(destination->data, buffer, 40);
 ...
 
+
+     VARHDRSZ is the same as sizeof(int4), but
+     it's considered good style to use the macro VARHDRSZ
+     to refer to the size of the overhead for a variable-length type.