#include <iostream> #include <cstring> using namespace std; #define SIZE 100 char buf[SIZE]; char* p = buf; char* alloc(int n) { char* begin; if (p + n <= buf + SIZE) { begin = p; p = p + n; return(begin); } else return(NULL); } int main() { char* p1, * p2; int i; p1 = alloc(10); strcpy(p1, "123456789"); p2 = alloc(5); strcpy(p2, "abcd"); cout << "buf=" << (void*)buf << endl; cout << "p1=" << (void*)p1 << endl; cout << "p2=" << (void*)p2 << endl; cout << p1 << endl; cout << p2 << endl; for (i = 0; i < 15; i++) cout << buf[i]; return 0; }修改它使得用vs能运行
时间: 2024-01-31 12:03:39 浏览: 58
这段代码在Visual Studio中需要进行以下修改才能运行:
1. 将头文件的包含语句从一行分成两行:
```
#include <iostream>
#include <cstring>
```
2. 去掉"using namespace std;",改为使用std::前缀。
3. 将strcpy函数改为strcpy_s函数。strcpy_s函数是一个安全的函数,它会检查目标数组的大小,防止缓冲区溢出。
4. 将指向buf的指针p的初始化改为以下形式:
```
char* p = &buf[0];
```
最终修改后的代码如下:
```
#include <iostream>
#include <cstring>
#define SIZE 100
char buf[SIZE];
char* p = &buf[0];
char* alloc(int n) {
char* begin;
if (p + n <= buf + SIZE) {
begin = p;
p = p + n;
return(begin);
}
else
return(NULL);
}
int main() {
char* p1, * p2;
int i;
p1 = alloc(10);
strcpy_s(p1, 11, "123456789");
p2 = alloc(5);
strcpy_s(p2, 6, "abcd");
std::cout << "buf=" << (void*)buf << std::endl;
std::cout << "p1=" << (void*)p1 << std::endl;
std::cout << "p2=" << (void*)p2 << std::endl;
std::cout << p1 << std::endl;
std::cout << p2 << std::endl;
for (i = 0; i < 15; i++)
std::cout << buf[i];
return 0;
}
```
经过以上修改,该代码能够在Visual Studio中成功编译和运行。
阅读全文