使用new运算符的问题 [英] problem in using new operator

查看:111
本文介绍了使用new运算符的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <iostream.h>
#include <conio.h>

void main()
{
    clrscr();
    int *p1,*p2,n,i;
    cout<<"Enter the size of the array ";
    cin>>n;
    p1=new int[n];
    p2=p1;
    for(i=0;i<n;i++)
        cin>>*p2++;
    p2=p1;
    for(i=n;i>0;i--)
        cout<<*p2--;
    getch();
    }

}





i输入值到使用new运算符创建的数组并想要打印这些反向排列的值但是

程序输出错误



i进入

1

2

resut是13262而不是2 1



i input values into array created using new operator and want to print these values in reverse order but
program give wrong output

i enter
1
2
resut is 13262 instead of 2 1

推荐答案

看看你在做什么:

你分配n个元素,然后加载它们中的n。第一个循环后指针在哪里?

答案:指向最后一个循环后的元素。



所以当你尝试 cout 第二个循环中的值,第一个访问是一个不存在的元素...



在纸上尝试使用n = 2的值,你会看到我的意思。
Look at what you are doing:
You allocate "n" elements, and then load "n" of them. Where is the pointer after the first loop?
Answer: pointing at the element after the last one.

So when you try to cout the values in the second loop, the first access is to an element that doesn''t exist...

Try it on paper with a value of n=2 and you will see what I mean.


如果不改变太多,请尝试这样:
Without changing too much, try this instead:
#include <iostream.h>
#include <conio.h>

void main()
{
    clrscr();
    int *p1,n,i;
    cout<<"Enter the size of the array ";
    cin>>n;
    p1=new int[n];
    for(i=0;i<n;i++)
        cin>>p1[i];
    for(i=n;i>0;i--)
        cout<<p1[i-1];
    delete [] p1;
    getch();
}

问候,

Ian。

Regards,
Ian.


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

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