Point me in the right direction

William E. Davidsen Jr davidsen at steinmetz.ge.com
Fri Feb 24 03:34:30 AEST 1989


In article <3735 at arcturus> evil at arcturus.UUCP (Wade Guthrie) writes:

| This is all well and good, but what about arrays of structures?  Am I
| S.O.L. because of inter-array-element padding if I:
| 
| 	struct already_defined snarf[] = {...};
| 
| and then try to get the size by doing:
| 
| 	#define N_WHATEVER (sizeof(snarf)/sizeof(struct already_defined))

	This will work. The sizeof struct may not be the same as the sum
of the sizes of each element, but that's not what you want here, just
the number of elements. Struct padding is a real case of "the whole is
greater than the sum of its parts."

| or can I (portably)
| 
| 	int size;
| 	. . .
| 	size = sizeof(snarf)/(&snarf[1]-&snarf[0]);
                              ^^^^^^^^^^^^^^^^^^^
	This will (portably) evaluate to one... doubt like hell that's
what you intended. You might get what you want if you use
	((char *)&snarf[1] - (char *)&snarf[0])
but since it evaluates to "sizeof(struct already_defained)" why not
write it that way.

| (assuming, of course, that snarf has at least 2 elements. . .)

	Yes, you had better put "[2]" rather than "[]" in the original
declaration.

  I don't think there's a problem here to solve, the conventional way is
portable and works, but it was fun thinking about what the pointer
subtraction does.
-- 
	bill davidsen		(wedu at ge-crd.arpa)
  {uunet | philabs}!steinmetz!crdos1!davidsen
"Stupidity, like virtue, is its own reward" -me



More information about the Comp.lang.c mailing list