如何将NRU分页算法中的指定C++代码行转换为C语言
C++ 动态内存申请转C语言对应实现
你标注的for循环内的frametable[i] = new char[references];对应的C语言写法如下:
frametable[i] = (char *)malloc(references * sizeof(char));
其余同逻辑的C++转C写法补充,方便你完整转换代码:
- 一维char数组申请转换:
原C++代码:pages = new char[references];、faults = new char[references];
对应C代码:pages = (char *)malloc(references * sizeof(char)); faults = (char *)malloc(references * sizeof(char)); - 二级char指针数组申请转换:
原C++代码:frametable= new char*[numberofframes];
对应C代码:frametable = (char **)malloc(numberofframes * sizeof(char *)); - 输入输出语句转换:
原C++代码:
对应C代码:cout << "\nEnter the number of references of pages you want to have: "; cin >> references;printf("\nEnter the number of references of pages you want to have: "); scanf("%d", &references);
注意:
- 使用
malloc需要引入头文件#include <stdlib.h>,使用printf、scanf需要引入头文件#include <stdio.h>- 动态申请的内存使用完毕后需要手动释放,避免内存泄漏,释放顺序与申请顺序相反:先遍历释放每个
frametable[i],再释放frametable,最后释放pages和faults。
内容的提问来源于stack exchange,提问作者Alexander Valverde
相关产品推荐
相关产品推荐

