为什么输入小于等于3个数字按0结束的时候没问题,当输入超过3个数字后就会有应用程序错误
#include <iostream>
#include <stdio.h>
using namespace std;
void main()
{
int i,num=0,*a,ele;
a=new int[num];
while(1)
{
cout<<"input data:\n";
cin>>ele;
if(!ele)
{
break;
}
else
{
num++;
a[num-1]=ele;
}
}
for(i=0;i<num;i++)
printf("%d ",a[i]);
}
动态数组问题
答案:3 悬赏:70 手机版
解决时间 2021-02-13 12:15
- 提问者网友:绫月
- 2021-02-13 06:42
最佳答案
- 五星知识达人网友:一袍清酒付
- 2021-02-13 06:49
1.分配数组的时候num=0,所以没分配空间
2.数组写满了也要跳出循环
3.完事后要释放数组
改成:
#include <iostream>
#include <stdio.h>
using namespace std;
void main()
{
int i,num=0,*a,ele;
a=new int[10];
while(1)
{
cout<<"input data:\n";
cin>>ele;
if(!ele)
{
break;
}
else
{
num++;
a[num-1]=ele;
if(num>9)
break;
}
}
for(i=0;i<num;i++)
printf("%d ",a[i]);
delete a;
}
2.数组写满了也要跳出循环
3.完事后要释放数组
改成:
#include <iostream>
#include <stdio.h>
using namespace std;
void main()
{
int i,num=0,*a,ele;
a=new int[10];
while(1)
{
cout<<"input data:\n";
cin>>ele;
if(!ele)
{
break;
}
else
{
num++;
a[num-1]=ele;
if(num>9)
break;
}
}
for(i=0;i<num;i++)
printf("%d ",a[i]);
delete a;
}
全部回答
- 1楼网友:渊鱼
- 2021-02-13 09:28
动态数组的意义在于让用户指定数组的大小,之后再申请空间,例如:
int i,count;
cout<<"input the length of array:\n";
cin>>count;
int array[count];
for(i=0; i<count; i++){}
最后通过for指定循环次数进行赋值。。。
数组并不能真正的动态申请内存,只有链表才是真正意义上的动态申请内存,因为它可以申请一个节点空间链接到原链表的最后。数组则不可以,你的程序也是用指针操作,试图通过数组加指针的结合实现动态数组,其实也是不合理的。。。内存早就溢出了。。
- 2楼网友:酒醒三更
- 2021-02-13 07:50
几个问题:
1.动态数组就是用redim preserve 语句重新声明数组的下标;下标上界可以在你得到一个结果后用变量进行设定;如
dim zs() as long
n = 0
for i =1000 to 1000000
if 质数(i) then '质数函数用来判断参数是否为质数,是就返回true该函数就由你自己来做吧
n = n + 1
redim preserve zs(1 to n)
zs(n)=j
end if
2.计算某个整数范围内的全部质数后,得到一个zs数组,用以下代码显示在text控件里
for i= 1 to ubound(zs())
t = t & zs(i)
next i
text = t
3.第1个问题里最终的n值就是那个数域里所有质数的个数了。可以用函数ubound(zs())求得。
如需更完整详细代码的可留email
我要举报
如以上问答信息为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯