我試圖從一個函數獲取2個指針並在主打印它。模糊的東西是一個指針似乎已經恢復了它的值,而另一個指針卻沒有。而且這兩個指針在調用函數內部都有正確的值,就在返回之前。請告訴我,您是否可以識別阻止我獲得正確答案的程序錯誤。從函數返回指針。值不更新爲一個指針
#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()中。但腐爛正在給出命令的垃圾值(e^-42)。請在這裏幫助我。
我*知道*有*必須*是您要返回'(rots,trans)'(基本上拋出'rots'並剛剛返回'trans')的特定原因。但對於我的生活,我無法理解*爲什麼*。我猜內存泄漏是獎金?但真正的問題是,用'std :: vector'完全處於你的處置中,爲什麼你首先要動手分配*任何東西?你可能會感到震驚*有多少代碼會使用流提取和標準lib容器消失。 –
WhozCraig
2013-05-11 05:08:38
我更感興趣的是你爲什麼做出假設**如果你還不知道語言,那沒問題,但是如果你沒有閱讀RTFM,那根本就不行。 – 2013-05-11 05:15:36
感謝您的輸入。我知道我在C++方面的知識不如urs。對不起,你不像你一樣熟練。但我在這裏嘗試,所以我請求幫助。我很抱歉,如果它激怒你如此愚蠢的東西。 @WhozCraig我想要這兩個值,所以我回來了,但現在我明白返回不起作用。從中學到了一些東西,謝謝。我將查看向量並瞭解如何根據它的工作原理修改此代碼。再次感謝您的投入。 – 2013-05-11 05:21:10