Pointer

Hi everyone

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?

thank you.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
using namespace std;
void f( const int * ); // 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( const int *xPtr, int y )
{ 
	y = 100;
    const int *xPtr; // error: cannot modify a const object
    xPtr = & y;
   

} // end function f 
You have many mistakes, but I didn't understand well what you need to do. Can you repeat with other terms maybe?
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>
using namespace std;

void f( const int * ); // 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( const int *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)
Topic archived. No new replies allowed.