What I'm confused about is why does the pass by pointer work, I thought whenever we need to modify the original object, we have to point to the original pointer |
You're getting your wires crossed here. If you want to modify x in another function, you pass a pointer to x.
You only need a pointer to a pointer to x if you are modifying the pointer:
1 2 3 4 5 6 7 8 9 10 11 12
|
void ptr(int* p);
void ptrptr(int** p);
int main()
{
int v = 5;
int* p = &v;
ptr(&v); // can modify v
ptr(p); // same as ptr(&v). can modify v, but not p (ie: can't make 'p' point to something else)
ptrptr(&p); // can modify v and p (can make it point to something other than v)
}
|
why can't is just be: node *insert_at_front(string data, node *front) |
It can be.
As for your example, it's a little hard to explain because you're doing a dynamic allocation, but I'll try:
Here,
new int[len];
created an unnamed array. For purposes of this explanation, I will call this array U. U exists somewhere in memory, but because it has no name you can't access it directly. Instead, new gives you a pointer to it, which you are assigning to box.
Therefore, box points to U.
*box = 33;
Since box points to U, this line modifies the first element in the U array.
1 2 3
|
int *clearArray_1(int **boxes)
//...
clearArray_1(&box);
|
Here, we are effectively saying
int** boxes = &box;
. That is, we are making a pointer called boxes, which points to our pointer box, which points to U.
boxes -> box -> U
|
int *box_copy = *boxes;//box_copy pts to first elem of array: box
|
This line basically undoes the above
(&box)
. We make a new pointer box_copy, which equals whatever boxes points to. Since boxes points to box... we are effectively saying
int* box_copy = box;
. And since box pointed to U, box_copy now also points to U.
So we have:
boxes -> box -> U
box_copy -> U
The clearArray_2 version is similar:
1 2 3
|
int *clearArray_2(int *boxes)
//...
clearArray_2(box);//NB: array name is implicit pointer to first elem of array box
|
Firstly, your comment is incorrect. 'box' is not an array name, it's a pointer. U is the array, and it has no name because it's unnamed. box just happens to point to it.
That said, by passing box to the function, we are effectively saying
int* boxes = box;
, which means both boxes and box will point to the same thing: U.