As a beginner in C++, first thing I came accross for functions is that they use a copy of the argument, for example if we execute this :
void add (double x){
x=x+3;
}
int main(){
double x=2 ;
add(x) ;
}
Then x would actually be equal to 2, not 5. Later on, learning about pointers, I found the following :
void fill (int *t){
for (int j=0, j<10, j++){
t[j]=j;
}
int main(){
int* p;
p = new int[10];
fill(p);
}
Now if we print what p contains, we find that it's indeed filled by the integers. I have some trouble understanding why it does that as I feel like it should have been the same as the first function ?
Thanks.
titself, you modify the data it points to.xwould actually be equal to 2" isn't accurate; thexinmainwould be 2, but thexinaddwould be 5 (before it goes away).pcontains" you have to be very careful:pis a pointer, and it contains a memory address; nothing more. Your functionfilltreats that memory address as the first element in an array; that's okay, because that's what the code does, butpdoes not contain an array; it points to an array.addto modifyx, define the parameter as a reference (i.e. an alias):void add (double& y){ y=y+3; }