Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Sizeof | Data
C Basics
course content

Зміст курсу

C Basics

C Basics

1. Introduction
2. Data
3. Operators
4. Control Statements
5. Functions
6. Pointers

bookSizeof

Data Size

The sizeof() function is a staple in C programming. It helps determine the size (in bytes) of the specified object or type.

For instance, let's see how many bytes the int data type occupies:

c

main

copy
12345678
#include <stdio.h> int main() { printf("Size of int type: %d bytes\n", sizeof(int)); return 0; }

The int data type occupies 4 bytes.

Note

Bear in mind that different compilers might allocate varying byte sizes for the same data type.

Bits

A bit is the most basic unit of data a computer uses. Every byte consists of eight bits.

It was collectively decided by engineers to equate one byte to 8 bits because this configuration conveniently represents decimal numbers.

You've likely heard of the binary number system, which forms the foundation of computer operations.

At its essence, the goal is to represent numerical values we use in our daily lives using combinations of zeros and ones. Any number can be represented as a combination of powers of two.

For instance, the number 7 can be portrayed as "111", and here's the breakdown:

The values 0 or 1 don't inherently have mathematical significance; they merely indicate a bit's state.

  • 0 – the bit is inactive;
  • 1 – the bit is active.

The number 113, in binary, appears as "01110001":

Data Types

What distinguishes different data types? – Their byte size!

c

Main

copy
123456789101112
#include <stdio.h> int main() { printf("Size of int type: %d bytes\n", sizeof(int)); printf("Size of char type: %d bytes\n", sizeof(char)); printf("Size of double type: %d bytes\n", sizeof(double)); // double is like float, but better return 0; }

You can utilize the sizeof() function on an array to ascertain its size:

c

main

copy
12345678910
#include <stdio.h> int main() { int intArray[10]; printf("Size of int array: %d bytes\n", sizeof(intArray)); return 0; }

An array with 10 integer elements occupies 40 bytes, meaning each individual element consumes 4 bytes. If you divide the total array size by the size of one of its elements, you'll determine the array's element count:

c

main

copy
1234567891011121314151617
#include <stdio.h> int main() { int data[] = { 4,8,1,5,0,123,66,11, 64,2,7,78,-0,34,23,545, 98,890,65,32,412,6,5465, 87859,656534,324,324,456, 356,341,5654, 534,756,12 }; int sizeOfArray = sizeof(data) / sizeof(int); // or sizeof(data) / sizeof(data[0]); printf("Elements in an array: %d\n", sizeOfArray); return 0; }

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 2. Розділ 7
some-alt