By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
449,423 Members | 1,294 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 449,423 IT Pros & Developers. It's quick & easy.

pointer/array/function difficulty

P: 1
fairly new C++ programmer,

So in this program the first value i set for nu2 seems to be getting passed to the output the second one keeps outputting garbage. I am not sure if this has something to do with the way I am passing my array to my function or whether this has something to do with me not dealing with the pointers the right way:

Expand|Select|Wrap|Line Numbers
  1.  
  2. #include<iostream>
  3. #include<math.h>
  4.  
  5. using namespace std;
  6.  
  7.  
  8. double dot (double v1[2], double v2[2])
  9. {
  10. double z; 
  11. z = v1[0]*v2[0]+v1[1]*v2[1];
  12. return z;
  13. }
  14. double* gramschmidt(double v1[2], double v2[2])
  15.  
  16. {
  17.        double proj[2];
  18.        double * pointer;
  19.        double nu2[2];
  20.  
  21.        pointer = nu2;
  22.  
  23.        proj[0]=(dot(v1,v2)/dot(v1,v1))*v1[0];
  24.        proj[1]=(dot(v1,v2)/dot(v1,v1))*v1[1];
  25.  
  26.        nu2[0]=v2[0]-proj[0];
  27.        nu2[1]=v2[1]-proj[1];
  28.  
  29.  
  30.        return pointer;
  31.  
  32.  
  33. }
  34.  
  35.  
  36. int main()
  37.  
  38. {
  39.  
  40.     double v1[2];
  41.     double v2[2];
  42.  
  43.     double* v;
  44.     double c;
  45.  
  46.     v1[0]=1;
  47.     v1[1]=2;
  48.  
  49.     v2[0]=1;
  50.     v2[1]=6;
  51.     v=gramschmidt(v1,v2);
  52.     cout << *v << endl;
  53.     cout << *(v+1) << endl;
  54.     double newa[2];
  55.     newa[0]=*v;
  56.     newa[1]=*(v+1);
  57.     c=dot(v1,newa);
  58.     cout<<c<<endl;
  59.  
  60.     system("PAUSE");
  61.  return 0;   
  62. }
  63.  
Apr 2 '11 #1
Share this Question
Share on Google+
1 Reply


weaknessforcats
Expert Mod 5K+
P: 9,197
The gramschmidt function is returning the address of a local variable. Then you use that address in main()but the local variable is out of scope so you get an indeterminate result.
Apr 2 '11 #2

Post your reply

Sign in to post your reply or Sign up for a free account.