我在理解和使用指针方面非常薄弱。所以,请在这里帮助我。
我的目标是将数组指针的地址传递给函数,(即)指针指向的地址,并在函数中使用“*”运算符直接更新地址中的值,以避免任何返回值。此外,这个数组的长度必须在它被传递到的函数中动态改变。这是我的尝试。如果有更好的方法来更新变量的值,而无需从函数返回,请务必提及以帮助我。
但是我遇到了错误,因为我知道我做错了,但仍然想尝试我所知道的,因为我认为最好的学习方法是做尽可能多的错误。请在这里帮助我
这是主要功能
int main()
{
double *trans;
int *rots;
readctrls(rots,trans);
for(int i=0;i<trans.size();i++)
{
cout<<trans[i]<<endl<<rots[i];
}
}
在这里,我试图将指针数组的地址传递给函数 readctrls。然后,打印它的值。我没有提到尺寸,因为它将在函数后面确定。
该功能只是从文本文件中逐行读取数字并将这些数字存储在这两个数组中。readctrls 函数如下。
void readctrls(int*& rots,double*& trans)
{
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];
trans = new double[nol];
rots = new int[nol];
for(int i = 0; i<nol ; i++)
{
getline(inputs,lines[i]);
temp = lines[i];
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);
trans[j] = ::atof(subtemptrans.c_str());
rots[j] = atoi(subtemprots.c_str());
}
}
}
inputs.close();
}
非常感谢你们的帮助。我能够理解一点并更改了代码,并且现在能够编译而没有错误。但是,我从文件中读取并加载到数组中的值似乎并没有反映在主文件中。当我在函数中打印数组时,我从文件中获取了正确的值,但是当我在 main() 中打印时,我得到了零。请在这里帮助我。
这些是文件的内容
0.2 0
0.2 0
0.2 0
0.2 0
0.2 0
而打印'trans',它在函数中每行取第一个数字,得到正确的值。但是在主函数中打印时
0
0
0
0.2.
我在传递给函数时将指针更改为指针引用。请检查功能代码中的编辑。提前致谢。