Re: Problem understanding pass by value and pass by reference of
arrays and what happens in the memory
venkatagmail wrote:
Thank you Barry for making me realize the problem of const and non-
const reference and pointers. I wished I also understood how the
memory is allocated in detail when calling these different methods.
I have problems understanding linked lists where I pass a head node
pointer by value and by reference. In either case I am able to access
pass by reference IIF you create the list inside the function body,
then you assign the "created pointer to root" to the passed in
reference, then the function caller gain the side-effect, the passed in
parameter then points to the created list. after calling the function.
in C, we often use pointer to pointer for this goal.
the all the subsequent nodes until the end of the list, delete and
make modifications to them in the called function. I still want to
understand these things in terms of the memory allocation and
deallocation in heap and stack.
When accessing modifying the list you can only pass in the pointer to
the list only. As you don't change the passed in pointer to point to
another list(actually a node).
I have an idea for you,
You can use a debugger, like Visual C++, then you can see the the object
lays and how. Pay attention to when/what the variable is
assigned/initialized.
on reference, it's special, you can jump to the assembly code.
I was told that VC uses pointer-like stuff to implement it.
http://www.parashift.com/c++-faq-lite/references.html
TC++PL:
"In some cases, the compiler can optimize away a reference so that there
is no object representing that reference at runtime."
Reference is special, remember.
Here is exmaple when reference to pointer is used:
#include <iostream>
#include <cstddef> // NULL
int g_arr[] = {1, 2, 3};
void get_array(int*& arr, int& count)
{
arr = g_arr;
count = 3;
}
void print(const int* a, int count)
{
for (int i = 0; i < count; ++i)
std::cout << a[i] << ' ';
std::cout << std::endl;
}
int main()
{
int count = 0;
int* pi = NULL;
get_array(pi, count);
print(pi, count);
}