nounoursnoir
nounoursnoir

Reputation: 703

Declaring a pointer to struct creates a struct?

It seems to me like struct new_element *element = malloc(sizeof(*element)) creates a structure of type element, whereas I thought it would only create a pointer to it. The following code proves to me I'm wrong:

struct new_element
{
    int i;
    struct new_element *next;
};

int main(void)
{
    struct new_element *element = malloc(sizeof(*element));
    element->i = 5;
    element->next = NULL;
    printf("i = %d, next = %p\n", element->i, element->next);
}

Output:

i = 5, next = (nil);

element->i was given the value 5 and element->next was given the value NULL. Doesn't that mean that element points to a structure, which would mean that there is a structure that was created? I thought that malloc would only give a pointer the size needed in memory.

Upvotes: 3

Views: 1054

Answers (1)

dbush
dbush

Reputation: 223872

The variable element is a pointer. When you define it, that sets aside space for the pointer.

If you just did this:

struct new_element *element;

You've created a pointer. It just doesn't point anywhere.

When you then call malloc(sizeof(*element)), that sets aside space big enough for what element points to, i.e. an instance of struct new_element. You then point the variable element to this section of memory.

This syntax:

element->i = 5;

Is the same as:

(*element).i = 5;

It dereferences the pointer element, giving you a struct new_element, then you access the member i.

If you did this, as you suggested in the comments:

struct new_element *element = malloc(sizeof(element));

You're not allocating the proper amount of space. You're setting aside enough space for a struct new_element * instead of a struct new_element. If the struct is larger than a pointer to it (likely in this case, since it contains a pointer to its own type), then you end of writing past the end of the allocated memory when modifying one of the members. This invokes undefined behavior.

Upvotes: 10

Related Questions