re.m7
re.m7

Reputation: 85

Why size of struct in C increases when passed by reference

I have been trying to understand structs and how their sizes differ based on the order members are declared and how padding and alignment are associated with that.

When I declare the struct like the one you see below, I get the size of memory I expected which is 4 bytes.

typedef struct {
    int x;
} GPS;

int main()
{
   GPS st;
   st.x = 42;
   int size;
   size = sizeof(st);
   printf("\n Size: %d", size);
   return 0;
}

But when I pass the struct by reference to a function, the struct increases its size to 8 bytes and I'm not sure why. I read everything about bit alignment and padding but it doesn't seem that has anything with the increase in size.

typedef struct {
    int x;
} GPS;

int main()
{
   GPS st;
   st.x = 42;
   printStruct(&st);
   return 0;
}

void printStruct(GPS *stptr)
{
    int size;
    char *ch = (char *)stptr;
    size = sizeof(stptr);
    printf("Size: %i \n", size);
}

So my question is, why does the struct increase in size when passed by reference?

Upvotes: 0

Views: 635

Answers (2)

dbush
dbush

Reputation: 223699

The size isn't increasing. You're getting the size of something else.

In your printStruct function, stptr has type GPS *, i.e. a pointer to GPS. A pointer to a struct is different from a struct instance, so the sizes don't have to be the same.

Had you used sizeof(*stptr), i.e. the size of what stptr points to, you would have gotten the value you expect.

Upvotes: 7

ltd9938
ltd9938

Reputation: 1454

The pointer is 8 bytes. When you pass by reference you're actually sending a pointer not the actual struct.

Upvotes: 1

Related Questions