Hi,
I have a question regarding the references in C++.
Is it possible for dynamically allocate memory for reference variables(&var_name) using malloc or new?Also please provide me better way of deallocating the memory.
// allocate space if address is NULL
if (m_Address == NULL)
{
m_Address = (char *) malloc(i_Size);
cout<<"The dynamically allocated address is "<<hex<<&m_Address<<endl;
}
if (1 != fread(m_Address, i_Size, 1, l_file_ptr))
{
syserr_exit("%s, line %d, fread(%s) fail\n",
__FILE__, __LINE__, i_FileName) ;
}
m_SizeRead = i_Size ;
}
In this code char* &m_Address is a reference to a char pointer right?
And this is allocated memory dynamically as below:
// allocate space if address is NULL
if (m_Address == NULL)
{
m_Address = (char *) malloc(i_Size);
cout<<"The dynamically allocated address is "<<hex<<&m_Address<<endl;
}
A reference variable always referes to an object. A pointer can refer to an object or no object, in which case it takes the null value.
If you want to allocate memory, you must refer to that memory using a pointer and you must release it using a pointer. During the object's lifetime, you may refer to it using a reference or pointer.
Your function simuReadFile passes m_SizeRead and m_Address as reference variables. But they are really synonyms for some real BYTE and char* variables resepectively. So the lines you wrote are syntactically correct:
Hi.
let me define what is reference avriable first
1. Reference variable
C++ intriduces a new kind of variable known as the Reference variable. A reference variable provides an alias for a previously defined variable.
For Example
1 2 3
float total=100;
float &sum=total;
here sum is a reference variable to total.
here both the variables refer to the the same object .