Connecting Tech Pros Worldwide Forums | Help | Site Map

Question regarding int* const in function call.

Andrew Isaverdian
Guest
 
Posts: n/a
#1: May 10 '06
void MyFunc(int* const ptr)
{
ptr = new int[10];
........
}

In program

int main()
{
int a = 0;
int* ptr1 = &a;
...................
MyFunc(ptr1); // gcc, for example, complains that "new int[10]"
contradicts
//constantess of the function's argument
(pointer in our case).
// However, we are dealing with a private copy
of the pointer
//anyway (???)
}



Phlip
Guest
 
Posts: n/a
#2: May 10 '06

re: Question regarding int* const in function call.


Andrew Isaverdian wrote:

Are you trying to pass a pointer by reference? int *& ptr?
[color=blue]
> void MyFunc(int* const ptr)[/color]

That is a "top-level const", meaning "ptr is a constant pointer to an
integer". The pointer is constant, not the integer. int const * ptr would
mean "ptr is a pointer to a constant integer".

There's never a reason to put a top-level const at the interface to a
function.
[color=blue]
> {
> ptr = new int[10];[/color]

And that tries to change the pointer, not the pointed-to thing. It's const,
so you get an error.

--
Phlip
http://c2.com/cgi/wiki?ZeekLand <-- NOT a blog!!!


Jonathan Mcdougall
Guest
 
Posts: n/a
#3: May 10 '06

re: Question regarding int* const in function call.


Andrew Isaverdian wrote:[color=blue]
> void MyFunc(int* const ptr)[/color]

This is a const pointer to an int, which means you cannot change the
pointer, but you could change what's pointed at.
[color=blue]
> {
> ptr = new int[10];[/color]

Therefore, this is illegal, but

*ptr = 2;

would be ok.
[color=blue]
> }[/color]


Jonathan

Closed Thread