【问题标题】:Why is this instance of dynamic allocation not successful?为什么这个动态分配实例不成功?
【发布时间】:2021-03-09 02:01:04
【问题描述】:

我正在尝试创建一个将 10 提高到索引号的幂的程序(索引 0 为 1,索引 1 为 10,索引 2 为 100,等等)。当我运行这个程序时,它不会输出任何东西。有什么问题?

#include<iostream>
#include<cmath>
using namespace std;

int* powersOfTwo(int n);

int* powersOfTwo(int n)
{
    int i, x=10;
    n=3;
    
    int *arr = new int(n);
    
    for (i=0; i<=n; i++) {
        
        arr[i]=pow(x, i);
        
        cout<<arr[i]<<endl;
        
    }



    return 0;

}



int main() {

    powersOfTwo;

    
    return 0;
}

【问题讨论】:

  • int int(n)new int[n] 不同。此外,即使修复了此错误,您的数组访问也会越界。
  • @John3136 powerOfTwo; 对函数求值,结果被丢弃。它不做任何事情,但它会编译。而0 将返回一个int* 空指针值。
  • 你甚至没有调用你的函数。你是从哪本书上学习 C++ 的?
  • @W.W.Atkinson C++ 不能真正自学。它具有未定义行为的概念。这意味着不可能通过试验和观察来学习。您看到的行为可能是标准行为,也可能是未定义行为的结果。如果不通过权威来源查找所有内容,您将无法知道。你需要一本好书或某种同等资源来学习 C++。
  • 既然您是自学成才,请忽略您学到的有关动态内存分配的任何知识。使用std::vector,可以通过引用传递。

标签: c++ dynamic-memory-allocation cout pow


【解决方案1】:

您可能希望在不调用pow 的情况下循环执行操作:

void powerOfTwo(std::vector<int>& powers, int quantity)
{
  int power = 1;
  powers.push_back(power);
  for (int i = 0; i < quantity; ++i)
  {
    power = power * 10;
    powers.push_back(power);
  }
}

int main()
{
  std::vector<int> database;
  powersOfTwo(database, 10);
  for (int i = 0; i < 10; ++i)
  {
     std::cout << " " << database[i];
  }
  std::cout << "\n";
  return 0;
}

注意事项:

  1. 向量是通过引用传递的,所以可以修改。
  2. 没有强制动态内存分配;没有泄漏。
  3. 向量将根据需要展开。
  4. 10 的幂将通过 power 或幂的数学定义来计算。
  5. 没有呼叫power;所有整数算术。

【讨论】:

    猜你喜欢
    • 2013-03-21
    • 2021-03-02
    • 1970-01-01
    • 2016-02-16
    • 2010-10-07
    • 2021-11-12
    • 2011-07-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多