[aclug-L] Re: Nice code and negative memory addresses
[Top] [All Lists]
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index] [Thread Index]
Lars von dem Ast wrote:
>
> Here's some nice code (taken from a C text):
>
> /* pmath.c */
>
> #define STRSIZ 20
>
> typedef struct {
> char name[STRSIZ];
> double diameter;
> int moons;
> double orbit_time, rotation_time;
> } planet_t;
>
> int main(void)
> {
> planet_t pl[2] = {{"Earth", 12713.5, 1, 1.0, 24.0},
> {"Jupiter", 142800.0, 4, 11.9, 9.925}};
> int nm[5] = {4, 8, 10, 16, 22};
> planet_t *p;
> int *np;
>
> p = pl + 1;
> np = nm + 1;
>
> printf("sizeof (planet_t) = %d sizeof (int) = %d\n",
> sizeof (planet_t), sizeof (int));
> printf("pl = %d nm = %d\n", pl, nm);
> printf(" p = %d (pl + %d) ", p, (int)p - (int)pl);
> printf("np = %d (nm + %d)\n", np, (int)np - (int)nm);
> printf(" p - pl = %d\n", p - pl);
>
> }
>
> Okay, here are the results:
>
> sizeof (planet_t) = 48 sizeof (int) = 4
> pl = -1073743632 nm = -1073743664
> p = -1073743584 (pl + 48) np = -1073743660 (nm + 4)
> p - pl = 1
>
> The pl, p, nm, and np variables should have memory addresses in them, but why
> are they negative numbers?
Because you told printf() to print the pointers as signed integers. printf
doesn't know better -- it just takes a sizeof(int) chunk of data off the
argument stack and does what you tell it to.
Instead of %d (signed integer), you could use %u (unsigned integer), or %x
(unsigned hexadecimal integer), or %p (some format appropriate for pointers,
usually hexadecimal, except that it will work even if sizeof(int) !=
sizeof(void*).
Also, your (int) casts are bogus. The proper cast of pointers to do byte address
calculations is to use (size_t). size_t is usually unsigned int or unsigned
long,
depending on the compiler and the machine architecture. It would also work to
cast both pointers to (char*), since sizeof(char) == 1.
> Lb
> -- This is the discussion@xxxxxxxxx list. To unsubscribe,
> visit http://tmp2.complete.org/cgi-bin/listargate-aclug.cgi
--
/*
* Tom Hull * thull at kscable.com * http://www.tomhull.com/
*/
-- This is the discussion@xxxxxxxxx list. To unsubscribe,
visit http://tmp2.complete.org/cgi-bin/listargate-aclug.cgi
|
|