I would some help with this code. I would like to print out the pointer in the main func. but as you see in the code the type of the pointer is constant so I cannot change the value through the pointer itself.
I create an int which is y so I can asign a value through it to the pointer.
Question is how I can print the value for the pointer?
#include <iostream>
usingnamespace std;
void f( constint * ); // prototype
int main()
{
int y;
f( &y ); // f attempts illegal modification
cout << xPtr;
} // end main
// xPtr cannot modify the value of constant variable to which it points
void f( constint *xPtr, int y )
{
y = 100;
constint *xPtr; // error: cannot modify a const object
xPtr = & y;
} // end function f
I would like to asigne value to the pointer and print it in the main func.
This is the main code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include <iostream>
usingnamespace std;
void f( constint * ); // prototype
int main()
{
int y;
f( &y ); // f attempts illegal modification
} // end main
// xPtr cannot modify the value of constant variable to which it points
void f( constint *xPtr )
{
*xPtr = 100; // error: cannot modify a const object
} // end function f
The problem is in your function prototype/header. You want to declare a const pointer, in that the address held by the pointer cannot be changed. However, what you're doing is declaring a pointer where the address held by it can be changed, but the value it points to cannot be. You simply need to move the const: void f( int * const xPtr)