Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commita370cad

Browse files
committed
Try to be a little less terse about dealing with variable-length structs
in C, but recommend that newbies who don't recognize this trick should dosome studying ...
1 parent7411493 commita370cad

File tree

1 file changed

+17
-6
lines changed

1 file changed

+17
-6
lines changed

‎doc/src/sgml/xfunc.sgml

Lines changed: 17 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
<!--
2-
$Header: /cvsroot/pgsql/doc/src/sgml/xfunc.sgml,v 1.42 2001/11/12 19:19:39 petere Exp $
2+
$Header: /cvsroot/pgsql/doc/src/sgml/xfunc.sgml,v 1.43 2001/11/14 22:14:22 tgl Exp $
33
-->
44

55
<chapter id="xfunc">
@@ -947,11 +947,18 @@ typedef struct {
947947
</para>
948948

949949
<para>
950-
Obviously, the data field shown here is not long enough to hold
951-
all possible strings; it's impossible to declare such
952-
a structure in <acronym>C</acronym>. When manipulating
950+
Obviously, the data field declared here is not long enough to hold
951+
all possible strings. Since it's impossible to declare a variable-size
952+
structure in <acronym>C</acronym>, we rely on the knowledge that the
953+
<acronym>C</acronym> compiler won't range-check array subscripts. We
954+
just allocate the necessary amount of space and then access the array as
955+
if it were declared the right length. (If this isn't a familiar trick to
956+
you, you may wish to spend some time with an introductory
957+
<acronym>C</acronym> programming textbook before delving deeper into
958+
<productname>Postgres</productname> server programming.)
959+
When manipulating
953960
variable-length types, we must be careful to allocate
954-
the correct amount of memory andinitialize the length field.
961+
the correct amount of memory andset the length field correctly.
955962
For example, if we wanted to store 40 bytes in a text
956963
structure, we might use a code fragment like this:
957964

@@ -962,9 +969,13 @@ char buffer[40]; /* our source data */
962969
...
963970
text *destination = (text *) palloc(VARHDRSZ + 40);
964971
destination-&gt;length = VARHDRSZ + 40;
965-
memmove(destination-&gt;data, buffer, 40);
972+
memcpy(destination-&gt;data, buffer, 40);
966973
...
967974
</programlisting>
975+
976+
<literal>VARHDRSZ</> is the same as <literal>sizeof(int4)</>, but
977+
it's considered good style to use the macro <literal>VARHDRSZ</>
978+
to refer to the size of the overhead for a variable-length type.
968979
</para>
969980

970981
<para>

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp