栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

由浅到深全面解析指针,这次彻底把指针搞明白

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

由浅到深全面解析指针,这次彻底把指针搞明白

指针在c/c++里属于难理解的知识点,在学习指针之前先来回顾一下变量的知识点,我们知道数据存储在计算机里有3个基本属性(1.数据存储在何处,2.存储的值是多少,3.存储的数据是什么类型)必须要跟踪。下面用一个整形和一个字符串型来做例子,代码如下:

// pointer.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include 
#include 

int _tmain(int argc, _TCHAR* argv[])
{
	using namespace std;
	int i=3;
	string str="zdsoft";
	cout<<"i="<// pointer.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include 
#include 

int _tmain(int argc, _TCHAR* argv[])
{
	using namespace std;
	int i=3;
	string str="zdsoft";
	cout<<"i="<// pointer.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include 
#include 

int _tmain(int argc, _TCHAR* argv[])
{
	using namespace std;
	int i=3;
	string str="zdsoft";
	int* pInt; //声明一个指针
	pInt=&i; //把i的地址赋值给pInt指针
	cout<<"i="<// pointer.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include 
#include 

int _tmain(int argc, _TCHAR* argv[])
{
	using namespace std;
	int i=3;
	string str="zdsoft";
	int* pInt; //定义一个指针
	pInt=&i; //把i的地址赋值给pInt指针
	cout<<"i="<#include "stdafx.h"
#include 
#include 

int _tmain(int argc, _TCHAR* argv[])
{
	using namespace std;
	int i=3;
	string str="zdsoft";

	int* pInt; //声明一个类型为int的指针
	string* pStr; //声明一个类型为string的指针

	pInt=&i; //把变量i的地址赋值给pInt指针
	pStr=&str;//把变量str的地址赋值给pStr指针

	cout<<"变量i的地址="<<&i<int* pInt=&i;
string* pStr=&str;

此时指针pInt是变量i的地址,指针pStr是变量str的地址。 

至此,如果你认真的看完了上面的文章,应该对指针有了初步的认识了。但是,如果你认为自己这就会用指针了,那就大错特错了,这只是初步了解。我们离全面了解还有很大一段距离。

使用指针时容易发生的危险,在C++中创建指针时,计算机只会分配用来存储地址的内存,但不会分配用来存储指针所指向数据的内存。为数据提供空间是一个独立的步骤,忽略这一步无疑是自找麻烦,比如下列代码:

// pointer.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include 
#include 

int _tmain(int argc, _TCHAR* argv[])
{
	using namespace std;
	int* pInt;
	*pInt=123;
	cout<<"pInt="<
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1014813.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号