logo

Каллок на С

У цій темі буде обговорено, як створити динамічний розподіл пам’яті за допомогою функції calloc() мовою програмування C. Перш ніж ознайомитися з поняттями, давайте обговоримо динамічний розподіл пам’яті в C. Динамічна пам’ять — це процедура структурного програмування, яка дозволяє користувачам виділяти пам’ять під час виконання програми. Використовуючи динамічний розподіл пам'яті, ми можемо збільшувати або зменшувати пам'ять під час виконання програми. Таким чином, це дозволяє уникнути втрати пам’яті комп’ютера. Виділення пам’яті ділиться на дві частини: malloc() і calloc().

Каллок на С

А функція calloc(). це попередньо визначена функція бібліотеки, яка означає безперервний розподіл пам'яті . Функція calloc() використовується для створення кількох блоків під час виконання програми, які мають однаковий розмір у пам’яті. Функція calloc визначена всередині stdlib.h файл заголовка. Він має два параметри, ні. блоків і розмір кожного блоку. Коли динамічна пам’ять виділяється за допомогою функції calloc(), вона повертає базову адресу першого блоку, і кожен блок ініціалізується 0. І якщо пам’ять не створюється, повертається покажчик NULL.

Наприклад, припустімо, що ми хочемо створити три блоки пам’яті за допомогою функції calloc(), нам потрібно передати два параметри, кількість блоків (3) і розмір кожного блоку (int, char, float тощо) у байт. Таким чином він створює три блоки однакового розміру в пам’яті комп’ютера.

Синтаксис

 ptr = (cast_type *) calloc ( number_of_blocks, size_of_block); 

У наведеному вище синтаксисі функція calloc() має два параметри. Перший параметр визначає кількість блоків а другий параметр визначає розмір кожного блоку в пам'ять. Розмір блоків і cast_type може бути int, char, float тощо.

Повернення : повертає базову адресу першого блоку до змінної ptr.

Програма для перевірки динамічної пам'яті виділяється за допомогою функції calloc().

Давайте напишемо просту програму, щоб перевірити, чи виділена динамічна пам'ять у C.

програма.c

 #include #include int main() { int *ptr; /* use calloc() function to define the no. of blocks and size of each blocks. */ ptr = calloc (4, sizeof(int)); // here 4 is the no. of block and int is the size of block if (ptr != NULL) { printf (' Memory is created successfully 
'); } else printf (' Memory is not created '); return 0; } 

Вихід:

 Memory is created successfully 

Програма для демонстрації використання функції calloc().

Давайте розглянемо створення динамічного розподілу пам’яті за допомогою функції calloc() і збереження даних у блоках пам’яті.

що таке hashset java

Program2.c

 #include #include #include void main() { int n, *ptr, *p, i, sum = 0; /* n = number of elements, *ptr = store base address of the dynamic memory, *p store temporary address of the *ptr */ printf (' Enter the number of elements: '); scanf (' %d', &n); // it takes number of elements // use calloc syntax to create memory block of int data type ptr = (int *) calloc (n, sizeof(int)); p = ptr; // assign the address of ptr if (ptr == NULL) // it checks whether the memory is allocated { printf (' Memory is not allocated. '); exit(0); // exit from the program } printf (' Enter %d numbers 
&apos;, n); for ( i = 1; i <= n; i++) { scanf ( '%d', ptr); sum="sum" + *ptr; ptr++; } printf (' elements are: '); for (i="1;" i <="n;" %d', *p); p++; 
 the addition of is: %d ', sum); getch(); pre> <p> <strong>Output:</strong> </p> <pre> Enter the number of elements: 5 Enter 5 numbers 1 2 3 4 5 Elements are: 1 2 3 4 5 The addition of the elements is: 15 </pre> <h3>Program to release dynamic memory allocation using free() function</h3> <p> <strong>free() function:</strong> A free() function is used to release the dynamic memory which is created either <strong>calloc</strong> () or <strong>malloc</strong> () function. These allocated memories cannot be freed to their own, and they will exist till the end of the program. So, it is our responsibility to release that memory that can be reused, and hence we explicitly use the free() function to release the memory.</p> <p> <strong>Syntax</strong> </p> <pre> free (ptr); </pre> <p>Here free() is a function that releases the allocated memory using the pointer ptr variable.</p> <p>Let&apos;s consider creating dynamic memory allocation using the calloc() function and then releasing occupied space using the free() function in the C program.</p> <p> <strong>Release.c</strong> </p> <pre> #include #include #include void main() { int n, *ptr, *p, i, sum = 0; printf (&apos; Define the number of elements to be entered: &apos;); scanf (&apos; %d&apos;, &amp;n); // use calloc syntax to create memory block of int data type ptr = (int *) calloc (n, sizeof(int)); p = ptr; // store the base address in p if (ptr == NULL) { printf (&apos; Out of memory &apos;); exit(0); } printf (&apos; Enter the elements 
&apos;, n); for ( i = 1; i <= n; i++) { scanf ( '%d', ptr); sum="sum" + *ptr; ptr++; } printf (' elements are: '); for (i="1;" i <="n;" %d', *p); p++; 
 the addition of is: %d ', sum); free(ptr); * use free() function to release dynamic memory allocation getch(); pre> <p> <strong>Output:</strong> </p> <pre> Define the number of elements to be entered: 6 Enter the elements 2 4 6 8 10 12 Elements are: 2 4 6 8 10 12 The addition of the elements is: 42 </pre> <hr></=></pre></=>

Програма для звільнення динамічного розподілу пам’яті за допомогою функції free().

функція free(): Функція free() використовується для звільнення створеної динамічної пам’яті calloc () або malloc () функція. Ці виділені пам’яті не можна звільнити як власні, і вони існуватимуть до кінця програми. Отже, наша відповідальність — звільнити ту пам’ять, яку можна використовувати повторно, і тому ми явно використовуємо функцію free() для звільнення пам’яті.

Синтаксис

 free (ptr); 

Тут free() — це функція, яка звільняє виділену пам’ять за допомогою змінної покажчика ptr.

Давайте розглянемо створення динамічного розподілу пам’яті за допомогою функції calloc(), а потім звільнення зайнятого простору за допомогою функції free() у програмі C.

Release.c

 #include #include #include void main() { int n, *ptr, *p, i, sum = 0; printf (&apos; Define the number of elements to be entered: &apos;); scanf (&apos; %d&apos;, &amp;n); // use calloc syntax to create memory block of int data type ptr = (int *) calloc (n, sizeof(int)); p = ptr; // store the base address in p if (ptr == NULL) { printf (&apos; Out of memory &apos;); exit(0); } printf (&apos; Enter the elements 
&apos;, n); for ( i = 1; i <= n; i++) { scanf ( \'%d\', ptr); sum="sum" + *ptr; ptr++; } printf (\' elements are: \'); for (i="1;" i <="n;" %d\', *p); p++; 
 the addition of is: %d \', sum); free(ptr); * use free() function to release dynamic memory allocation getch(); pre> <p> <strong>Output:</strong> </p> <pre> Define the number of elements to be entered: 6 Enter the elements 2 4 6 8 10 12 Elements are: 2 4 6 8 10 12 The addition of the elements is: 42 </pre> <hr></=>