C++ 中 关于指针内存

最近在写一段代码的时候 遇到一个 小问题 

// c1.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
using namespace std;
int main(int argc, char* argv[])
{
    int *p,N;
    cin>>N;
   // p=(int *)malloc(N*sizeof(int));//分配了动态数组a[N]
    p=new int[N];
	for(int i=0;i<N;i++)
	{ 
		cin>>*(p);
		p++;
	}
	for(int j=0;j<N;j++)
	{
		cout<<*p<<endl;
	    p++;
	}
	return 0;
}
这里 P的类存指向发生了变化 。例如。你输入的N=2;输入的 两个数字为1,2.

假设 1对应的指针为0,2对应的指针为4,,,

则在输出的时候。第一个数字为  指针8对应的内容,依次类推。。。。。输出肯定是错的。。。

正确的如下

// c1.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
using namespace std;
int main(int argc, char* argv[])
{
    int *p,N;
    cin>>N;
   // p=(int *)malloc(N*sizeof(int));//分配了动态数组a[N]
    p=new int[N];
	for(int i=0;i<N;i++)
	{ 
		cin>>*(p+i);
	//	p++;
	}
	for(int j=0;j<N;j++)
	{
		cout<<*p<<endl;
	    p++;
	}
	return 0;
}
p始终是指向头地址的 ,但P+i就指向下一个地址 ,当在输入的时候  会发现p+i和p++  指向的是同一个地址。。。。。



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值