c++ - 扩展数组的输出返回意外的答案

标签 c++

根据教授要求的指针要求,我已经写完了一个包含数组反转、展开和移位的程序。一切都编译但 expand 函数的答案没有返回我想要的:在旧用户输入数组后添加 0,它要求数组的大小和你希望放入数组的数字。我认为我的问题可能在于我在程序中可能没有引用的东西上包含了一个指针。下面是我的代码:

// *numPtr refers to my old user input array and int tamaño is the size of the array


void expandArray(int *numPtr, int tamaño) {

    int *nuevoArray = new int[tamaño *2];

    for (int i = 0; i<tamaño; i++) {
        nuevoArray[i] = numPtr[i];
    }
    for (int i = tamaño; i < (tamaño*2); i++) {
        nuevoArray[i] = 0;
    }
    std::cout << nuevoArray << " ";
}

正如我所说,我认为代码没有按我希望的方式编译是因为我使用了 *nuevoArray 并且它在我的主要代码中没有引用,但话又说回来,我只是 C++ 的初学者。我想只做一个 vector ,但我想我不会遵循教授提出的指针要求。

最佳答案

如果要打印 nuevoarray 的内容,只需使用这样的 for 循环:

for (int i = 0; i < (tamaño*2); i++) {
  std::cout << nuevoArray[i] << " ";
}
std::cout << "\n";

此外,由于您正在使用 new[] 创建数组,因此您不应该忘记 delete[] 它!

关于c++ - 扩展数组的输出返回意外的答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33337477/

相关文章:

c++ - Linux shell模拟: stuck on multiple pipes

c++ - Lambda 函数参数 + 推导改进

c++ - 以下预编译是什么意思?

C++:根据模板参数设置指针的常量性

c++ - Float 或 Double 特殊值

c++ - 有效使用reinterpret_cast?

c++ - 创建字符指针和整数指针数组

c++ - 使用专门的模板根据返回类型重载函数

c++ - C++ 中内联函数的好处?

c++ - 操作数据成员时 : which of the following is considered best practice