remedial ptr question

Why am I able to assign the value of 7 here:

1
2
3
4
5
6
7
8
9
10
11
12
13
#include<iostream>

using namespace std;
int main()
{
	int name = 12;
	int * n_ptr = &name;
	*n_ptr = 7;
	cout<<*n_ptr;

	return 0;
}

7


But not here?

1
2
3
int * n_ptr;
*n_ptr = 7;
cout<<* n_ptr;


run time error
Last edited on
In your first code n_ptr is pointing to name so *n_ptr = 7; will assign the value 7 to name.

In your second code you have not told what n_ptr should point to so where are you trying to write the value 7? You can't be sure where n_ptr points to, but most probable is that it points to some memory location where your program is not allowed to write so that is why it crashes.
Last edited on
thx.
 
int * n_ptr = &name;


Are there any other valid structures n_ptr can point to besides &name?
Last edited on
Not in your small program, but if you had other int objects in your program you could make it point to any of them.
...
thank you
Topic archived. No new replies allowed.