Void pointers and pointer arithmetic
Brian T. Schellenberger
bts at sas.UUCP
Sun Jan 7 05:45:24 AEST 1990
In article <1990Jan3.073624.14061 at twwells.com> bill at twwells.com (T. William Wells) writes:
|In article <1055 at esatst.yc.estec.nl> arne at yc.estec.nl (Arne Lundberg) writes:
|:
|: I am trying to write some code that tries to access members in a structure
|: by knowing the start address and the offset to a particular member element.
|: The following program shows a small example (the real program does not
|: hardcode the offsets etc.) Is this program legal in ANSI C, will it
|: produce the desired result?
|:
|: The (Non-ANSI) compilers I have tested either gives the value for `a'
|: three times or complains about ``unknown size for pointer to void''.
|: It works perfectly well if I change the type of p to be ``char *''.
|:
|: ---------------------------------------
|: struct x {
|: int a, b, c;
|: } x = {
|: 1, 2, 3
|: };
|:
|: main()
|: {
|: void *p = &x;
|: printf("a %d\n", *(int *)(p + 0));
|: printf("b %d\n", *(int *)(p + 4));
|: printf("c %d\n", *(int *)(p + 8));
|: }
|: ---------------------------------------
. . . so just use "char *"; this works under ANSI, too.
1. offsetof is the size in bytes. (4.1.5)
2. sizeof yields the sie in bytes;
When applied to char . . . the result is 1. (3.3.3.4)
3. A pointer to void shall htave the representation and
alignment requirements as a pointer to character type (3.1.2.5,
the paragraph just before examples).
Ergo, this must work under ANSI with char *.
--
-- Brian, the Man from Babble-on. ...!mcnc!rti!sas!bts
-- (Brian Schellenberger)
"No one will ever write a song called 'Nitro Burning Funny Cars'"
-- THE DEAD MILKMEN, "Nitro Burning Funny Cars"
More information about the Comp.std.c
mailing list