显示用户创建的数组中的数字

Displaying numbers from a user created array c++

本文关键字:数字 数组 显示 创建 用户      更新时间:2023-10-16

好吧,这可能是一个非常简单的问题,我只是很新的c++和努力理解大多数东西。我被要求创建一个存储随机数的数组,但用户要定义数组的大小。然后我必须显示数组中的所有数字。我正在努力显示数组的所有元素。目前,我很确定我已经得到了数组部分,但我似乎只能显示一个数字。下面是我到目前为止的代码:

#include <iostream>
#include <cstdlib>
#include <stdlib.h>
#include <ctime>
using namespace std;
using std::srand;
using std::rand;
using std::time;
void Display(int *, int);
int main(void)
{
    int userSize;
    cout << "Please enter the size of the array: ";
    cin >> userSize;
    int* randArray = new int[userSize];
    srand(time(NULL));
        for (int i = 0; i < userSize; i++) {
        randArray[i] = rand() % 20 + 1;
        }
        //Disregard the next few lines, I was just testing to see if anything was actually in the array. 
        /*cout << randArray[0] << endl;
          cout << randArray[1] << endl;
          cout << randArray[2] << endl;
          cout << randArray[19] << endl;*/
    Display(randArray, sizeof(randArray) / sizeof(int));
    return 0;
    delete[] randArray;
}
void Display(int *arrayData, int numElements)
{
    for (int counter = 0; counter < numElements; counter++)
    {
    std::cout << *(arrayData + counter) << std::endl;
    }
    return;
}

我还应该提到,老师提供给我们的代码后面的行删除数组。

这是我必须回答的问题:询问用户要在数组中存储的元素数量。然后,您应该动态分配内存来保存该数组,该数组将以与前一个任务相同的方式继续使用(用随机数据填充数组,将数据显示给屏幕)。

sizeof(randArray)没有告诉您已分配的字节数。相反,它告诉您指针的大小,在您的系统中,它恰好与整数的大小相同,因此sizeof(randArray) / sizeof(int)总是返回1。相反,使用userSize作为Display函数调用中的第二个参数。

同样,return 0之后是delete[] randArray。这是不正确的;return 0之后不会执行任何操作。你想把它放在上面。

进一步,考虑使用std::vector来代替(除非您需要为这个赋值使用一个原始指针)

问题是sizeof。它给出了参数类型的大小,而不是后面的内容。您应该将userSize传递给Display()

你也应该在return之前delete数组。return后面的代码永远不会被执行。