Hello, i coded a chunk. the chunk seems to work fine except that the loop doesn't work.I have asked some questions at lines where i have doubt.I will appriciate if sum1 guides me through my doubts.
#include<iostream>
usingnamespace std;
void area(int,int); //area() with parameters of type int.
void price (int*); //price() with parameters type int pointer.
int l;
int w;
int a;
int *p1(&a); //declaring the pointer p1 value which points to adress of a.&=reference pointer.
int main() {
cout<<"******************************************************"<<"\n";
cout <<"This program includes passing arguments via pointers."<<"\n";
cout<<"******************************************************"<<"\n";
cout<<"enter length: ";
cout<<"\n";
cin>>l;
cout<<"\n";
cout<<"enter width: ";
cout<<"\n";
cin>>w;
cout<<"\n";
area(l,w); //area() called with arguments l & w.
return 0;
}
void area(int l,int w) {
a=l*w;
price(p1); //price() with argument that is a pointer p ?? (can't i use int *p1)??
}
void price(int *p1) {
int pr;
cout<<"please fix the price: "<<"\n";
cin>>pr;
int p;
int i(0);
for (int i=0;i<2;i++) {
p=pr*(*p1); //wont value in p1 overwritten with every loop??
int *p1=&p; // here i have overridden the value of *p1 to &p which was before &a in line 8.(isnt it possible?)
cout<<"area: "<<p<<endl;
i++;
}
}
1.) It is defined that way: void price (int*); //price() with parameters type int pointer.
2.) What are you doing here is: p = pr * (*p1)
or in English:
p gets the value of pr times p1 derefenced (whatever the global p1 is pointing to)
So, no, p1 won't be overwritten.
3.) You aren't overwriting p1. You are declaring a new (local variable) called p1 and assigning it to p. This variable is destroyed (nothing is done with it either) at the end of the loop.
line 39: int *p1=&p; // here i have overridden the value of *p1 to &p which was before &a in line 8.(isnt it possible?)
dint this change the value??
another thing is that i am not a native english speaker so
1.) It is defined that way: void price (int*); //price() with parameters type int pointer.
dint get me.. or i dint get that..did u mean that declaring price(p1); on line 28 can also be written as price(*p1); or the declaration of price() in line 4 takes care of the rest.i needn't write [code]price(*p1);[/code in 28?? sorry if i m not able to clarify my point.
You are creating and modifying a new local variable, not the global one.
That is the way the function is defined. It returns nothing and takes a pointer to an integer as a parameter. e.g.
1 2 3 4 5 6 7 8 9
void price(int*);
int main() {
int x = 20;
int* my_ptr = &x; //create a pointer to an int
price(my_ptr); //pass it to the function (we don't need to do anything else because price just wants a pointer to an int
//...
return 0;
}