c++ - Pass pointer array address to function and update data in the address -
i pretty weak in understanding , working pointers. so, please me here.
my objective pass array pointer's address function ,(i.e.) address pointer pointing to, , update values directly in address using '*' operator, in function, avoid return values. moreover, length of array has changed dynamically in function passed. attempt. if there's better method update value of variable, without having returned function, please mention me.
but getting errors, know doing wrong, still wanted try know, since thought best way learn , make many mistakes possible. please me here
this main function
int main() { double *trans; int *rots; readctrls(rots,trans); for(int i=0;i<trans.size();i++) { cout<<trans[i]<<endl<<rots[i]; } }
here, trying pass address of pointer arrays function readctrls. later, print values. haven't mentioned size, cuz determined later in function.
the function read numbers text file, line line , store these numbers in these 2 arrays. readctrls function follows.
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 = 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(); }
thanks lot guys. able understand bit , changed code , able compile without errors. however, value read file , load array, doesn't seem reflected in main. getting correct values file when print array in function, getting zeros, when print in main(). please me here.
these contents of file
0.2 0 0.2 0 0.2 0 0.2 0 0.2 0
while print 'trans', takes first number every line, in function, getting correct values. while printing in main function
0 0 0 0.2.
i changed pointer pointer reference while passing function. please check edit in function code. in advance.
the declaration
void readctrls(int &rots,double &trans)
tells compiler rots
, trans
references single value each. not pointers.
to make matters worse, trying pass pointer-to-pointer arguments when calling function.
you should change declaration take pointers:
void readctrls(int* rots, double* trans)
then change call not use address-of operator (as pointers):
readctrls(rots, trans);
Comments
Post a Comment