【问题标题】:C++ Dynamic Arrays CreationC++ 动态数组创建
【发布时间】:2021-06-26 18:38:42
【问题描述】:

我的问题提示如下

  1. 编写一个打印动态数组的程序。
  2. 程序创建一个包含 3 个元素的 int 1D 动态数组和 3 ROWS 和 3 COLS 的浮点 2D 动态数组。
  3. 用随机值初始化两个数组。
  4. 两个数组将在两个单独的函数中分别打印
  5. void print_2d_array(float**);
  6. void print_1d_array(int*);"

我创建了一个不会产生任何输出的代码。我猜问题出在数组的初始化中,但我无法弄清楚。如何让它显示随机生成的数字?

#include <iostream>
#include <iomanip>

using namespace std;

void print_2d_array(float**);
void print_1d_array(int*);

int main() {
    srand(time(NULL));

    int* arr[3];
    float** arr_two[3][3];

    for (int i = 0; i < 3; i++)
        *arr[i] = rand() % 100;
    
    for (int j = 0; j < 3; j++)
        for (int k = 0; k < 3; k++)
            **arr_two[j][k] = rand() % 100;

    print_1d_array(*arr);
    print_2d_array(**arr_two);
}

void print_2d_array(float** arr_two) {
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++)
            cout << arr_two[i][j];
    }
    cout << endl;
}

void print_1d_array(int* arr) {
    for (int i = 0; i < 3; i++)
        cout << arr[i];
}

【问题讨论】:

  • int* arr[3]; -- 这是不正确的。你了解new[]吗?您的代码中没有任何地方使用过它。现在,您的代码到处都使用未初始化的指针。

标签: c++ arrays dynamic


【解决方案1】:

您永远不会为 1D int 数组分配内存,也不会为 float 2D 数组分配内存。您的声明也是错误的,例如 float** arr_two[3][3] 是一个大小为 3 的数组,其中包含指向 float 的指针的大小为 3 的数组,显然不是您想要的。

您的代码应该看起来更像这样:

int *arr = new int[3]; // pointer to int will hold 3 ints

float **arr_two = new float *[3]; // array of 3 pointers to float

for (int i = 0; i < 3; i++)
{
    arr_two[i] = new float[3]; // each pointer will hold 3 floats
}

for (int i = 0; i < 3; i++)
    arr[i] = rand() % 100; // indexing is the same as if it was an array[size]

for (int j = 0; j < 3; j++) // indexing is the same as if it was an array[size][size]
    for (int k = 0; k < 3; k++)
        arr_two[j][k] = rand() % 100;

print_1d_array(arr); // you pass the name of the pointers, no dereference needed
print_2d_array(arr_two);

您还应该在打印函数中打印一些空格和换行符,否则这将看起来像一个非常大的单个值。

另外,当您不再需要数据时,不要忘记释放内存:

delete[] arr;

for (int i = 0; i < 3; i++)
{
    delete[] arr_two[i];
}

delete[] arr_two;

我还应该提到,在现代 C++ 中,我们很少看到原始指针的使用(可能在 SO 问题中除外)。替代方案是:

另请注意,您的随机值都是int,因此您不会在float 数组中看到float 值。如果你想随机生成小数值,你需要一个新的方法,看看这里:Random float number generation

【讨论】:

  • 谢谢@anastaciu,这消除了我对指针和新 int/float 用法的误解。我很欣赏准确的回应。
  • @StudentTryingHisbest 很高兴为您提供帮助,只要您尽力而为 ;)
猜你喜欢
  • 2018-01-13
  • 2016-02-22
  • 1970-01-01
  • 1970-01-01
  • 2016-04-09
  • 1970-01-01
  • 1970-01-01
  • 2013-12-16
  • 1970-01-01
相关资源
最近更新 更多