C++:传递和返回指向数组的指针——代码不工作

标签 c++

<分区>

我正在尝试编写一个将 int 数组转换为 double 的函数。它接受一个指向原始 int[] 数组的常量指针(以避免不必要的修改?)并返回一个指向转换后的 double[] 数组的指针。但是,我编写的代码似乎不起作用。任何人都可以指出它有什么问题吗?

#include <iostream>
using namespace std;
double* castToDouble(const int *input);

int main(){
    int integers[] = {1,2,3,4};
    double *doubles = castToDouble(integers);
    cout << "numElements in doubles: " << sizeof(doubles)/sizeof(double) << endl;
    for(int i = 0; i < sizeof(doubles)/sizeof(double); i++){
       cout << doubles[i] << endl;
    }
    return 0;
}

double* castToDouble(const int *input){
    // Obtain the number of elements in input.
    int numElements = sizeof(input)/sizeof(int);
    double *doubleAry = new double[numElements];
    cout << "numElements in input: " << numElements << endl;
    for(int i = 0; i < numElements; i++){
        doubleAry[i] = static_cast<double>(input[i]);
    }
    return doubleAry;
}

程序的输出如下:

numElements in input: 2
numElements in doubles: 1
1

计算的 numElements 似乎也是任意的。我是 c++ 的新手,无法查明问题所在。提前致谢。

最佳答案

当您将其标记为 C++ 时,我认为这可能更符合习惯:

#include <vector>
#include <algorithm>

std::vector<double> CastToDouble(std::vector<int> const & ints)
{
    auto doubles = std::vector<double>(ints.size());

    std::transform(ints.begin(), ints.end(), doubles.begin(), [](int value) -> double {
        return static_cast<double>(value);
    });

    return doubles;
}

int main(int argc, char* argv[])
{
    auto values = std::vector<int>() = { 
        1, 2, 3, 4
    };

    auto doubles = CastToDouble(values);
}

关于C++:传递和返回指向数组的指针——代码不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29212204/

相关文章:

C++ 相关的继承层次

c++ - Stack.pop 内存管理

c++ - 如何在 Visual Studio 2010 Express 的 Win32 应用程序中使用 Win32 类库?

c++ - 为什么我使用移位运算符 (C++) 得到随机结果?

c++ - 如何在 C++ 中终止程序

c++ - 如何在 C++ 中实现多维映射的常量正确性

C++ FMOD Studio 无法为 freq 的 FMOD DSP PARAMETER FFT 赋值。分析

c++ - Stack walk with inline asm for VC++

c++ - C++数组中初始化列表的类型是什么?

c++ - `RAWINPUT::header::wParam`包含什么用于键盘输入