raj wrote:
Hi all.
I am little bit confsused with the way pointer is working. First of all
what is the difference between
int &Number = 10;
and
int *Number;
int & Number = 10;
This is an error. Only const references can be initialized with
temporaries.
You can do this :
int temp = 10;
int & Number = temp;
Now Number is a reference to an integer, initialized with temp.
Alternatively, you can also use :
const int & Number = 10;
constant references can be initialized by literals and temporaries.
Further, int *Number defines an un-initialized pointer to integer. The
pointer is named as "Number".
One more question ...
void Copy(char **word)
{
*word = [some pointer to a string];
}
when calling this function with
char **sentence;
Copy(sentence); //Here the application crashes
but when calling this function with
char *sentence;
Copy(&sentence); //Here it works fine.
What is wrong i do in the first call of function.
Saying "char** sentence" defines only a pointer to char*. It doesnot
reserve any memory for the char*. Hence, when you dereference char **
inside the function, you get some junk value and that memory doesnot
belong to you. Attempting to write on that memory yields a seg-fault.
In the second case, when you say char *sentence, you are reserving the
space for char* on the stack. So that memory is yours, and the copy
function is legally writing in your stack area. Hence no crash.