C programming - standard library stdlib.h
The "stdlib.h" header file in C programming provides functions that are used for memory allocation, converting data types, generating pseudo-random numbers, sorting, and other general-purpose functions.
Some of the commonly used functions in "stdlib.h" include:
"malloc": Allocates a block of memory of a specified size.
"calloc": Allocates a block of memory for an array of elements, initializing them to zero.
"realloc": Changes the size of a previously allocated block of memory.
"free": Releases a block of memory previously allocated with "malloc", "calloc", or "realloc".
"atoi": Converts a string to an integer.
"atof": Converts a string to a double.
"rand": Generates a pseudo-random integer.
"srand": Seeds the pseudo-random number generator used by "rand".
"qsort": Sorts an array of elements using a specified comparison function.
Here is an example of using the "stdlib.h" header file in a C program:
#include <stdio.h> #include <stdlib.h> int main() { int *arr = malloc(5 * sizeof(int)); if (arr == NULL) { printf("Error allocating memory\n"); return 1; } for (int i = 0; i < 5; i++) { arr[i] = rand() % 10; } printf("Unsorted array: "); for (int i = 0; i < 5; i++) { printf("%d ", arr[i]); } printf("\n"); qsort(arr, 5, sizeof(int), compare); printf("Sorted array: "); for (int i = 0; i < 5; i++) { printf("%d ", arr[i]); } printf("\n"); free(arr); return 0; } int compare(const void *a, const void *b) { const int *ia = (const int *)a; const int *ib = (const int *)b; return (*ia - *ib); }
In this example, the "stdlib.h" header file functions are used to allocate and free memory, generate pseudo-random numbers, and sort an array of integers. The "malloc" function is used to allocate a block of memory for an array of integers, and the "rand" function is used to generate random integers to fill the array. The "qsort" function is used to sort the array using a comparison function defined by the user. Finally, the "free" function is used to release the memory allocated with "malloc". The output of the program will be:
Unsorted array: 8 7 0 1 6 Sorted array: 0 1 6 7 8
Note that the behavior of the functions in "stdlib.h" is platform-dependent, and they may differ between different implementations of C.