Welcome to our deep dive into the C stdlib.h Library! This library is a treasure trove of functions that makes working in C easier and more efficient. Let's explore its wonders together.
The stdlib.h is a standard library in C programming. It provides various utility functions that help in memory management, mathematical operations, string handling, and more.
Memory management is crucial when working with C. The stdlib.h library offers functions to help manage memory efficiently.
malloc() is a function used to dynamically allocate memory of a specified size.
#include <stdlib.h>
int main() {
int *ptr;
int size = 10;
ptr = (int *) malloc(size * sizeof(int));
// Now you have an array of size 10
// Remember to free memory when done!
return 0;
}free() is used to deallocate memory that was previously allocated using malloc().
#include <stdlib.h>
int main() {
int *ptr;
int size = 10;
ptr = (int *) malloc(size * sizeof(int));
// Use the memory
free(ptr); // Deallocate memory when done
return 0;
}stdlib.h library also provides functions for mathematical operations that aren't directly supported by C.
atoi() is a function that converts a string into an integer.
#include <stdlib.h>
#include <stdio.h>
int main() {
char str[] = "123";
int num = atoi(str);
printf("Integer value of %s is %d\n", str, num);
return 0;
}String handling in C can be tricky, but stdlib.h comes to our rescue with several functions.
strcmp() is a function used to compare two strings lexicographically.
#include <stdlib.h>
#include <stdio.h>
int main() {
char str1[] = "Hello";
char str2[] = "World";
int result = strcmp(str1, str2);
if(result < 0) {
printf("%s comes before %s\n", str1, str2);
} else if(result > 0) {
printf("%s comes after %s\n", str1, str2);
} else {
printf("%s is equal to %s\n", str1, str2);
}
return 0;
}What does `malloc()` function do in C?
Remember, the more you practice, the more you learn! Happy coding! 💻🎉