#include<iostream> #include<string> using namespace std; //全局变量 int a; int b; //const修饰的全局常量 const int e = 0; const int f = 0; int main() { //静态变量 static int c; static int d; cout << "以下是他们的地址" << endl; cout <<"全局变量a:"<< (int)&a << endl; cout <<"全局变量b:"<< (int)&b << endl; cout << "静态变量c:" << (int)&c << endl; cout << "静态变量d:" << (int)&d << endl; //const 修饰的全局常量 cout << "全局常量e:" << (int)&e << endl; cout << "全局常量f:" << (int)&f << endl; //字符串常量 cout << "字符串常量g:" <<(int)&"pppp" << endl; cout << "字符串常量h:" <<(int)& "qqqq" << endl; system("pause"); return 0; }改正
时间: 2023-08-20 13:41:04 浏览: 116
使用include <iostream>时一定要加using namespace std
这段代码存在几个问题:
1. 在头文件中缺少#include<cstring>,应该加上以使用字符串常量。
2. 在输出字符串常量的地址时,应该使用指针类型,而不是用int类型强制转换。
3. 代码缺少注释,不便于阅读和理解。
下面是改正后的代码:
```c++
#include<iostream>
#include<string>
#include<cstring> //添加头文件
using namespace std;
//全局变量
int a;
int b;
//const修饰的全局常量
const int e = 0;
const int f = 0;
int main() {
//静态变量
static int c;
static int d;
//输出各种变量的地址
cout << "以下是他们的地址" << endl;
cout <<"全局变量a:"<< (int)&a << endl;
cout <<"全局变量b:"<< (int)&b << endl;
cout << "静态变量c:" << (int)&c << endl;
cout << "静态变量d:" << (int)&d << endl;
cout << "全局常量e:" << (int)&e << endl;
cout << "全局常量f:" << (int)&f << endl;
//字符串常量
char g[] = "pppp"; //定义一个字符串数组
char h[] = "qqqq";
cout << "字符串常量g:" << static_cast<void*>(g) << endl; //使用指针类型输出字符串常量的地址
cout << "字符串常量h:" << static_cast<void*>(h) << endl;
system("pause");
return 0;
}
```
阅读全文