关于c++中内存空间分配的问题

来源:百度知道 编辑:UC知道 时间:2024/05/16 13:52:57
#include <iostream>

using namespace std;

#define MAX_NUM 1000

bool odd(const int num,const int *array);
int main()
{
int *arr = new int(2);
int *tail = arr;
*(++tail) = '\0';
for (int num = 7; num <= MAX_NUM; num += 2)
{
if(odd(num,arr))
{
*tail = num;
tail++;
}
*tail = '\0';
}
for (int *temp = arr; *temp != '\0'; ++temp)
{
cout << *temp << endl;
}
return 0;
}

bool odd(const int num, const int *array)
{
while(*array != '\0')
{
if(num % (*array++) == 0)
return 0;
}
return 1;
}

当MAX_NUM为1000时程序还能正常运行,但是当MAX_NUM为10000的时候就会出内存错误。不知道为什么……
arr既然是在堆上开辟的空间,那么它指向的地址应该是堆中的地址啊,所以对它进行“++”操作应该还是在堆空间中分配吧
这个我不确定……

在我机器上1000不好用,
30我试了都不好用,
你这个程序是想实现什么啊?
int *arr = new int(2);
int *tail = arr;
上面是开了堆空间,然后怎么下面就不开了,后面都是用++来弄了,
这样,也不安全吧?你定义的也不是数组的.