+ 11

Is a pointer passed by value?

https://www.sololearn.com/discuss/315095/?ref=app Similar to this, I have tried creating various functions with the returning pointer as an argument and as a return value... In all of the return cases, the new pointer got updated with the values... But in most of the argument cases, the passed pointer remained blank, and didn't have any update at all... So how to solve this? Help. //This makes me conclude that pointers are passed by value, but that is impossible! //Pointers are memory representations!

24th Apr 2017, 1:31 AM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar
4 Respostas
+ 10
Consider: #include <iostream> using namespace std; void ptr_alt (int *p) { p = new int; } int main() { int *p = NULL; ptr_alt(p); cout << p; return 0; } // The result of pointer variable address will always be NULL. Consider: #include <iostream> using namespace std; void ptr_alt (int *&p) { p = new int; } int main() { int *p = NULL; ptr_alt(p); cout << p; return 0; } // Here, we pass the pointer variable by reference. Result of p will always contain dynamically allocated address. // Conclusion: Pointer variables are passed by value unless stated otherwise.
24th Apr 2017, 1:49 AM
Hatsy Rei
Hatsy Rei - avatar
+ 11
@rain_drop BTW... int main() { int no[100],esum=0,osum=0,n,a=0,b=0; cout<<"How many Numbers? - ";cin>>n; for(int i=0;i<n;i++) { cout<<"Enter Number "<<i+1<<" - "; cin>>no[i]; if(no[i]%2==0) { e[a]=no[i]; esum+=no[i]; a++; } else { o[b]=no[i]; osum+=no[i]; b++; } } cout<<"Even Numbers - "; for(int j=0;j<a;j++) { cout<<e[j]<<","; } cout<<"\nSum - "<<esum<<endl; cout<<"Odd Numbers - "; for(int k=0;k<b;k++) { cout<<o[k]<<","; } cout<<"\nSum - "<<osum<<endl; }
24th Apr 2017, 10:19 AM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar
+ 9
@rain_drop How is it related to my question?
24th Apr 2017, 10:05 AM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar
+ 8
So, a pointer is passed by value after all...
24th Apr 2017, 1:51 AM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar