从函数返回指针.一个指针的值未更新
return pointers from function. Value not updated for one pointer
我试图从函数中获得2个指针并在main中打印它。模糊的事情是一个指针似乎已经恢复了它的值,而另一个没有。两个指针,在调用函数中都有正确的值,就在返回之前。请告诉我,如果你能找出任何程序错误,阻止我得到正确的答案。
#include<iostream>
#include<fstream>
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
using namespace std;
double* readctrls()
{
fstream inputs;
inputs.open("input_coods.txt");
int nol = 0,i = 0;
string line,temp,subtemptrans,subtemprots;
while(getline(inputs,line))
{
++nol;
}
// cout<<nol<<endl;
inputs.close();
inputs.open("input_coods.txt");
string *lines = new (nothrow) string[nol];
double* trans = new double[nol];
double* rots = new double[nol];
trans[0] =float(nol);
for(int i = 0; i<nol ; i++)
{
getline(inputs,lines[i]);
// cout<<lines[i]<<endl;
temp = lines[i];
// cout<<temp<<endl;
for(int j = 0; j<temp.length() ; j++)
{
if(temp.at(j) == ' ')
{
subtemptrans = temp.substr(0,j);
subtemprots = temp.substr(j+1,temp.length()-j);
// cout<<subtemprots<<endl;
*(trans+i+1) = ::atof(subtemptrans.c_str());
*(rots+i) = float(atoi(subtemprots.c_str()));
// cout<<rots[i]<<endl;
}
}
}
inputs.close();
// cout<<rots[2]<<endl;
return(rots,trans);
}
int main()
{
double *trans,*rots;
(rots,trans) = readctrls();
// cout<<sizeof(trans)<<endl;
for(int i=0;i<trans[0];i++)
{
cout<<*(trans+i)<<endl;
cout<<*(rots+i)<<endl;
}
}
Trans的值在内存中写得很好,并且从main()中完全保留。但是rot给出的是(e^-42)数量级的垃圾值。
c++既不是Python也不是Lua。
一个函数不能返回多个值。
return rots, trans;
这是逗号操作符-计算其操作数并产生最后一个(最右边的)操作数。
(rots, trans) = readctrls();
同样地,这只赋值给trans
, rots
将不初始化。
解决方案:您可以返回包含两个指针的结构体,或通过引用传递它们,或其他…
struct Foo {
double *rots;
double *trans;
};
Foo readctrls()
{
// ...
Foo r;
r.rots = rots;
r.trans = trans;
return r;
}
或:
void readctrls(double *&r, double *&t)
{
// ...
r = rots;
t = trans;
}
其他备注:
不要使用原始数组。
在c++中读取整个文件只是为了计算行数,然后再次读取它以实际解析其内容,这是超级浪费。如果您使用
std::vector<double>
,那么您可以在执行过程中只使用vector.push_back(some_double);
,这样您就不必遍历文件两次(您知道,I/O非常昂贵,特别是当文件很大时)。你从来没有
delete
你使用new
分配的指针-这里你的程序泄漏内存
std::vector<T>
一般优于T *
。相关文章:
- 函数向量_指针有不同的原型,我可以构建一个吗
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- 引用一个已擦除类型(void*)的指针
- 修改函数中的指针(将另一个指针作为参数传递)
- 如何将指针从一个void函数传递到另一个C++
- 如何在没有数据拷贝的情况下从指针创建一个Eigen VectorXd对象
- 如果C++对象的类在另一个boost模块中声明,如何使用boost将指向该对象的指针返回到python
- 为什么我们要为avl树实现返回一个指向节点的指针,而不是void函数
- 不明白迭代器,引用和指针失效,一个例子
- 为什么C++对链表中的下一个节点使用指针,而像 C# 或 Java 这样的语言只使用类 Node 的名称?
- int数据类型的指针指向的是什么,如果是一个类的私有数据成员,我们创建了该类的两个对象?
- 将指针分配给另一个指针时会发生什么情况?
- 将指向给定子类的指针从一个向量复制到另一个向量
- C++将一个指针分配给另一个指针时执行的类型检查
- 创建一个棋盘格或"Interweave"两个链接列表。IE 更改两个链表的指针
- 给定一个指向堆分配内存的指针,智能指针实现如何为其找到合适的释放函数?
- 取消引用结束指针到数组类型的一个
- 更改一个指针后更改乘法对象
- const和指针(一个节点示例)
- 从函数返回指针.一个指针的值未更新