<cstdlib>
库
内存分配
malloc()
在堆上分配指定字节数的内存空间
| #include <cstdlib> |
| #include <iostream> |
| int main() { |
| int* ptr = (int*)malloc(sizeof(int)); |
| if (ptr!= nullptr) { |
| *ptr = 10; |
| std::cout << *ptr << std::endl; |
| free(ptr); |
| } |
| return 0; |
| } |
malloc()分配了足够存储一个int类型的内存空间
如果分配成功,它返回一个指向该内存块的指针(void*类型,所以需要进行类型转换)
free()函数用于释放由malloc()分配的内存,以避免内存泄漏
calloc()
与malloc()类似,
| #include <cstdlib> |
| #include <iostream> |
| int main() { |
| int* ptr = (int*)calloc(5, sizeof(int)); |
| if (ptr!= nullptr) { |
| for (int i = 0; i < 5; ++i) { |
| std::cout << ptr[i] << " "; |
| } |
| |
| std::cout << std::endl; |
| free(ptr); |
| } |
| return 0; |
| } |
realloc()
调整已被分配的内存块大小
| #include <cstdlib> |
| #include <iostream> |
| int main() { |
| int* ptr = (int*)malloc(3 * sizeof(int)); |
| if (ptr!= nullptr) { |
| for (int i = 0; i < 3; ++i) { |
| ptr[i] = i; |
| } |
| |
| ptr = (int*)realloc(ptr, 5 * sizeof(int)); |
| if (ptr!= nullptr) { |
| for (int i = 3; i < 5; ++i) { |
| ptr[i] = i; |
| } |
| for (int i = 0; i < 5; ++i) { |
| std::cout << ptr[i] << " "; |
| } |
| |
| std::cout << std::endl; |
| free(ptr); |
| } |
| } |
| return 0; |
| } |
程序终止
exit()
立即终止程序的执行 会执行一些清理操作
| #include <cstdlib> |
| #include <iostream> |
| int main() { |
| std::cout << "Before exit" << std::endl; |
| exit(0); |
| std::cout << "After exit (This line will not be executed)" << std::endl; |
| return 0; |
| } |
_Exit()
不会执行任何清理操作
数值转换
atoi()
将字符串转换为整数
| #include <cstdlib> |
| #include <iostream> |
| int main() { |
| char str[] = "123"; |
| int num = atoi(str); |
| std::cout << num << std::endl; |
| return 0; |
| } |
atol()
长整数
atof()
浮点数
随机数生成
rand()
生成一个伪随机整数
srand()
生成一个随机整数种子
| #include <cstdlib> |
| #include <iostream> |
| #include <ctime> |
| int main() { |
| srand(static_cast<unsigned int>(time(nullptr))); |
| |
| for (int i = 0; i < 5; ++i) { |
| std::cout << rand() << " "; |
| } |
| std::cout << std::endl; |
| return 0; |
| } |
系统相关
system()
| |
| #include <cstdlib> |
| #include <iostream> |
| int main() { |
| int result = system("ls"); |
| std::cout << "System command return value: " << result << std::endl; |
| return 0; |
| } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)