Saturday, May 22, 2010

In C++, the difference between the following?

constant pointer to a character array.


pointer to a constant character array.


constant pointer to a constant character array.


Please explain with the correct notations.


Thanks.

In C++, the difference between the following?
constant pointer to a character array. : pointer always points to the array, but the contents of the array can change.





pointer to a constant character array.: pointer points to an array whose contents are fixed.





constant pointer to a constant character array.: none can be changed.
Reply:you can't change a constant pointer's value. it will always point to the same memory location.





char chrArray[] = { 'H', 'i', '!' };


int *const cPtr = %26amp;chrArray; // constant pointer to char array





const char chrArray[] = { 'H', 'i', '!' };


int *cPtr = %26amp;chrArray; // pointer to constant char array





const char chrArray[] = { 'H', 'i', '!' };


int *const cPtr = %26amp;chrArray; // constant pointer to constant char array
Reply:Character array is computer memory (stored at address1) where it is stored a set of characters which constitutes this array.





Pointer is again computer memory (stored at address2), which stores the value which is again an address (in this case address1).





Constant is modifier keyword which makes the specified computer memory is protected in a context.





Constant pointer to character array =%26gt; Pointer is protected but not the array pointed to by this pointer. So you cannot make this pointer to point to any other character array but you can change the pointing character array to store different characters.





pointer to a constant character array =%26gt; Pointer is not protected but the memory this points is. So you cannot modify the content of the character array but you can change pointer to point to any other location.





constant pointer to a constant character array =%26gt; In this case memory places are protected and you cannot change any of them.





Hope that helps.


No comments:

Post a Comment