数组赋值问题

时间:2013-09-19 21:50:39

标签: c++ arrays

我遇到输出数组的问题。当我输出每个元素而没有for循环时,程序运行正常。当我尝试使用for循环输出时,程序在第一次在数组中设置元素时崩溃。当我取消注释for循环时,我已经标记了程序崩溃的行。我的排序似乎工作正常,程序在此之前崩溃,所以我很确定这不是问题。任何想法为什么第二个for循环会使程序在指定的行崩溃?

int main()
{
   int* Array;
   int j = 5;
   for(int i=0; i<5; i++)
   {
       Array[i] = j; //Crashes here with 2nd for loop uncommented
       cout << Array[i] << endl;
       j--;
   }
    Array = insertion_sort(Array);

    cout << Array[0] << endl;
    cout << Array[1] << endl;
    cout << Array[2] << endl;
    cout << Array[3] << endl;
    cout << Array[4] << endl;



   /*for(int k=0; k <5; k++)
   {
      cout << Array[k] << endl;
   }*/


}

2 个答案:

答案 0 :(得分:3)

在初始化之前,您正在访问指针。你应该改变

int* Array;

int* Array = new int[5]; // There are 5 ints in my array

并确保

delete[] Array;

最后,甚至更好:

int Array[5]; // This way you don't need the new keyword, so you won't need to delete[] later

答案 1 :(得分:1)

目前,您的阵列尚未实现。它只是一个指针。在开始写入数组之前,您需要选择所需的数组大小。

int* Array = new int[5];
int j = 5;
for(int i=0; i<5; i++)
{
    Array[i] = j; //Crashes here with 2nd for loop uncommented
    cout << Array[i] << endl;
    j--;
}
相关问题