关于指针的问题 [英] question about pointer

查看:79
本文介绍了关于指针的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <iostream.h>
#include <conio.h>
void main()

{

clrscr();
int *p1;
int n,i;
cout<<"Enter size of array ";
cin>>n;
p1=new int[n];
for(i=0;i<n;i++)
cin>>*p1++;
cout<<"output values "<<endl;
for(i=0;i<n;i++)
cout<<*p1++;

getch();
}



我的程序没有给出正确的输出哪里是逻辑中的错误


my program not give the correct output where is the mistake in logic

推荐答案

在开始输出循环之前将p1指针重置回数组的开头!
Reset the p1 pointer back to begin of the array before you start your output loop!


1。输出有问题,你的输入中已经改变了p1,在你的cin之后,p1指向了数组的末尾。



2.为什么还在使用
1. Problem with your output, you''ve changed p1 in your input, after your cin, p1 has pointed to the end of the array.

2. why still using
iostream.h

这太旧了......试试

It''s too old... Try

#include <iostream>
using namespace std;





3.记得删除你的指针。



3. remember to delete your pointer.


你需要在指针处保存指针,当你开始第二个循环时恢复它:

You need to save the pointer at teh start, and restore it when you are startign the second loop:
int *p1, *pStart;
int n,i;
cout<<"Enter size of array ";
cin>>n;
pStart=new int[n];
p1 = pStart;
for(i=0;i<n;i++)
   cin>>*p1++; 
cout<<"output values "<<endl;
p1 = pStart;
for(i=0;i<n;i++)
   cout<<*p1++;
delete [] (pStart);

请注意,您应该养成在完成任务时删除任何内容的习惯!

Note that you should also get into the habit of deleting anything you allocate when you are finished with it!


这篇关于关于指针的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆