最近在写一段代码的时候 遇到一个 小问题
// 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++ 指向的是同一个地址。。。。。