简体   繁体   中英

How can I access the attribute of an struct using simple pointer arithmetic?

I have this struct along with the method that initializes it:

struct Person 
{
    char name[32];
    char lastn[32];
    size_t year;
};

void init_pers(struct Person* p, const char* n, const char* ln, size_t y)
{
    strcpy(p->name, n);
    strcpy(p->lastn, ln);
    p->year = y;
}

And this is the way they're called in the main:

struct Person f;
init_pers(&f, "Alan", "Wake", 1995);

By simple pointer arithmetic I was able to print the two first attributes:

printf("First field: %s\n", (const char*)&f); // prints 'Alan'
printf("Second field: %s\n", (const char*)&f + 32); // prints 'Wake'

However when I try the same to print the third attribute, which is a size_t, I get a number other than the year:

printf("Third field: %lu\n", (size_t)&f + 64); // prints '6422317'

What's the right way to print the space of memory that holds the year using pointer arithmetic?

The C standard doesn't really specify how struct members are laid out; there may be padding.

Instead of assuming that year is 64 bytes into the struct, you should be using offsetof(struct Person, year) .

If you need more control over how the struct is laid out in memory, look into packed structs. It's not standard, but pretty much all compilers support them, though the syntax is different.

That said, that third printf isn't doing what you think. Try something like

*((size_t*) (((char*) &f) + 64))

With your original code you're trying to print the address of year as a size_t , not the value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM