【问题标题】:Having trouble printing out the first two numbers in a dynamically allocated array, the other numbers work fine无法在动态分配的数组中打印出前两个数字,其他数字工作正常
【发布时间】:2017-02-03 18:26:53
【问题描述】:
#include <iostream>
#include<cstdlib>
#include<ctime>

using namespace std;

int* randomNumbers(int min, int max, int size);
int main()
{
    int min = 20;
    int max = 100;
    int size = 10;
    int* nums; 

    nums = randomNumbers(min,max,size); 
    cout << "***************"<<endl;

    for(int i = 0; i < size;i++)
    {
        cout << *(nums+i) << endl; 
    }


    return 0;

}


int* randomNumbers(int min, int max, int size)
{
    int* random = new int[size]; 
    unsigned seed = time(0); //time elapsed since Jan 1, 1970
    srand(seed);

    for (int i = 0;i<size;i++)
    {
        *(random+i) = rand() % ((max+1)-min) + min;
        cout<<*(random+i)<<" ";

    }

     cout<<endl;

    delete[] random; 
    return random;
}

因此,如果我在 Xcode(Macbook) 中运行此代码,它会完美运行,但是如果我在 Codeblocks(Windows) 中运行此代码,则从 main 函数打印的前两个数字以百万为单位,但从打印的前两个数字randomNumbers() 在预期范围内。我不明白为什么在主函数中打印数字会改变前两个值?其余的都很好。我真的口齿不清,请随时就我的问题提出问题。

【问题讨论】:

  • delete[] random; return random; 这不可能是正确的。
  • a[i]*(a+i) 更易读(也更不容易出错)。
  • 欢迎来到 Stack Overflow。请花时间阅读The Tour 并参考Help Center 中的材料,您可以在这里问什么以及如何问。

标签: c++ arrays pointers random dynamic-allocation


【解决方案1】:
   delete[] random; 
   return random;

你正在删除你的数组!

删除数组后对数组的任何访问都是未定义的。完成后清理数组。

将删除移到这里:

 for(int i = 0; i < size;i++)
 {
     cout << *(nums+i) << endl; 
 }

 delete[] nums;
 return 0;

【讨论】:

  • 不推荐这样的 c++ 代码。有更好的方法来实现动态存储分配
  • 请花一点时间修复缩进。如果 OP 能做对,你也应该能做对。
猜你喜欢
  • 2013-04-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-23
相关资源
最近更新 更多