C++指针

来源:互联网 发布:java特种兵 读后感 编辑:程序博客网 时间:2024/04/30 01:19
#include <iostream>
//使用命名空间
using namespace std;
int main() {
 cout << "HelloWorld!\n";
 int i,j;
 int tsum;
 j = 2;
 for(i = 1; i <= 10; i ++){
   j *= 2;  
 }
 tsum = j;
 std::cout << tsum;
 std::cout << "\n";
 //所有指针都应该初始化
 //指针 :存储内存地址的变量,指针的类型必需跟变量的类型一致
 //声明:类型名+*(星号)
 //初始化:可以使用变量,也可以使用等于0的指针来初始化
 int* pint = 0; //用0初始化的指针为空指针
 string* pstr;
 string str = "我是字符串类型的变量";
 //获取变量tsum的地址 ,使用(地址)运算符'&' 给指针变量赋值;
 pint = &tsum;
 pstr = &str;
 //简接运算符'*'(星号):输出指针所指向的内存位置的内容
 cout << *pint;
 cout << "\n";
 cout << pstr; //输出字符串pstr在内存的位置
 cout << "\n";
 cout << *pstr;//输出字符串pstr在内存中位置的内容
 cout << "\n";
 //空指针的判断:(pint == 0) 或者 (!pint)
 if(pint == 0){
  cout << "pint is null point!";
 }else{
  cout << "pint is " << pint << " point!";  
 }
 
}
原创粉丝点击