Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Behaviour of sizeof operator in C

Tags:

c

struct

sizeof

I am getting unusual behaviour with my code, which is as follows

#include<stdio.h>
struct a
{
    int x;
    char y;
};
int main()
{   
   struct a str;
   str.x=2;
   str.y='s';
   printf("%d %d %d",sizeof(int),sizeof(char),sizeof(str));
   getch();
   return 0;
}

For this piece of code I am getting the output:

4 1 8

As of my knowledge the structure contains an integer variable of size 4 and a char variable of size 1 thus the size of structure a should be 5. But how come the size of structure is 8. I am using visual C++ compiler. Why this behaviour?

like image 317
Jainendra Avatar asked Apr 26 '12 11:04

Jainendra


People also ask

What is the use of sizeof () operator in C?

You can use the sizeof operator to determine the size that a data type represents. For example: sizeof(int); The sizeof operator applied to a type name yields the amount of memory that can be used by an object of that type, including any internal or trailing padding.

Why is sizeof () an operator and not a function?

In C language, sizeof( ) is an operator. Though it looks like a function, it is an unary operator. For example in the following program, when we pass a++ to sizeof, the expression “a++” is not evaluated. However in case of functions, parameters are first evaluated, then passed to function.

What is mean by sizeof operator explain with example?

For example, when the sizeof operator is executed with integer (int) as a parameter, it always returns the number four to indicate that a variable of integer type occupies four bytes of memory.

How does the sizeof function work?

The sizeof keyword refers to an operator that works at compile time to report on the size of the storage occupied by a type of the argument passed to it (equivalently, by a variable of that type). That size is returned as a multiple of the size of a char, which on many personal computers is 1 byte (or 8 bits).


1 Answers

It is called Structure Padding

Having data structures that start on 4 byte word alignment (on CPUs with 4 byte buses and processors) is far more efficient when moving data around memory, and between RAM and the CPU.

You can generally switch this off with compiler options and/or pragmas, the specifics of doing so will depend on your specific compiler.

Hope this helps.

like image 59
Binary Worrier Avatar answered Oct 04 '22 06:10

Binary Worrier