将整数转换为数字数组 C++ 的函数

a function which convert integer to an array of digits c++

本文关键字:C++ 函数 数组 数字 整数 转换      更新时间:2023-10-16
#include<iostream>
using namespace std;
int *Arr(int y,int size){
int arg[size];
for(int i=size-1;i>=0;i--){
    arg[i]=y%10;
    y=y/10;
}
return arg;
}
int main(){
int *p=Arr(2587,4);
for(int j=0;j<4;j++){
  cout<<p[j]<<"   ";
}
return 0;
}
> Blockquote

我不知道为什么这不起作用...我正在尝试支持一个数组,但问题出在第二位数字上。有人可以帮忙;)谢谢

问题是您将结果放入一个本地数组中,该数组在函数结束时被销毁。您需要动态分配数组,以便其生命周期不限于创建它的函数:

#include<iostream>
using namespace std;
int *Arr(int y, int size)
{
    // This local array will be destroyed when the function ends
    // int arg[size];
    // Do this instead: allocate non-local memory
    int* arg = new int[size];
    for(int i = size - 1; i >= 0; i--)
    {
        arg[i] = y % 10;
        y = y / 10;
    }
    return arg;
}
int main()
{
    int *p = Arr(2587, 4);
    for(int j = 0; j < 4; j++)
    {
        cout << p[j] << "   ";
    }
    // You need to manually free the non-local memory
    delete[] p; // free memory
    return 0;
}

注意:

如果可能,应避免使用 new 分配动态内存。您可能需要研究用于管理它的智能指针

此外,在实际C++代码中,您将使用像std::vector<int>这样的容器而不是内置数组

当然它不起作用。

充其量,行为是未定义的,因为Arg()返回的局部变量的地址 (arg) 不再存在 main() . main()使用该返回的地址,当它不是就您的程序而言存在的任何内容的地址时。

还有一个附带的问题,即int arg[size],其中size在编译时未修复,C++无效。 根据编译器的严格程度(某些编译器拒绝无效C++C++构造,但其他编译器接受此类扩展(,您的代码甚至无法成功编译。

要解决此问题,请让您的函数返回一个std::vector<int>(vector是在标准标头<vector>中定义的模板化容器(。 然后,您的函数需要做的就是将值添加到本地向量中,该向量可以通过值安全地返回给调用方。

如果你做得对,你甚至不需要在代码中的任何位置使用指针。