将整数转换为数字数组 C++ 的函数
a function which convert integer to an array of digits c++
#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>
中定义的模板化容器(。 然后,您的函数需要做的就是将值添加到本地向量中,该向量可以通过值安全地返回给调用方。
如果你做得对,你甚至不需要在代码中的任何位置使用指针。
相关文章:
- "error: no matching function for call to"构造函数错误
- 什么时候调用组成单元对象的析构函数
- 继承函数的重载解析
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- C++模板来检查友元函数的存在
- 递归函数计算序列中的平方和(并输出过程)
- 对RValue对象调用的LValue ref限定成员函数
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 在C++STL中是否有Polyval(Matlab函数)等价物?
- 为什么使用 "this" 指针调用派生成员函数?
- 将对象数组的引用传递给函数
- 函数调用中参数的顺序重要吗
- 函数向量_指针有不同的原型,我可以构建一个吗
- 使用不带参数的函数访问结构元素
- 代码在main()中运行,但在函数中出现错误
- 内置函数可查看CPP中的成员变量
- 如何获取std::result_of函数的返回类型
- 如何在c++中为模板函数实例创建快捷方式
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗