Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is pointer to struct a pointer to its first member?

I'm learning how to work with structs in C and wrote the following example:

#include <stdio.h>
#include <stdlib.h>

struct s1{
    unsigned short member;
};

int main()
{
    struct s1 *s1_ptr = malloc(sizeof(*s1_ptr));
    s1_ptr -> member = 10;
    printf("Member = %d\n", *s1_ptr); // Member = 10
}

QUESTION: Is it guaranteed that in all cases a pointer to a struct is a exactly the same pointer to its first element?

In this particular case it works as I expected, but I'm not sure if it is guaranteed. Is compiler free to insert some padding in the very beginning?

The only I could find about the structure type layout is the Section 6.2.5 Types of N1570:

A structure type describes a sequentially allocated nonempty set of member objects (and, in certain circumstances, an incomplete array), each of which has an optionally specified name and possibly distinct type.

But there is nothing about padding here.

like image 333
St.Antario Avatar asked Dec 24 '22 02:12

St.Antario


2 Answers

The padding at the start is covered by 6.7.2.1p15 (emphasis mine)

Within a structure object, the non-bit-field members and the units in which bit-fields reside have addresses that increase in the order in which they are declared. A pointer to a structure object, suitably converted, points to its initial member (or if that member is a bit-field, then to the unit in which it resides), and vice versa. There may be unnamed padding within a structure object, but not at its beginning.

So the address of a struct is the address of of its first member. And following a pointer conversion, you are able to obtain one from the other.

like image 164
StoryTeller - Unslander Monica Avatar answered Dec 28 '22 16:12

StoryTeller - Unslander Monica


Well, not exactly perhaps, but at least castable.

A pointer to a struct can be cast to a pointer to its first member (or, if the member is a bit field, to its allocation unit). Likewise, a pointer to the first member of a struct can be cast to a pointer to the enclosing struct. There may be unnamed padding between any two members of a struct or after the last member, but not before the first member.

So you should be able to do it.

like image 25
bipll Avatar answered Dec 28 '22 17:12

bipll