The following code is giving run-time error when I change only the place of one line of code. Actually this is no program or snippet, I am just trying to get concept. SO ANY BODY Could help me what is going on here. I am using dev-C++ to run it.
//This is a template I use to understand the concepts of c++
#include<iostream.h>
#include<stdlib.h>
#include<conio.h>
main()
{
int x,*yptr; //Declaring an integer x and pointer yptr
int *zptr; //Declaring a pointer zptr
x=3; //Assigning value to variable x
yptr=&x; //Storing address of variable x at pointer yptr
cout<<yptr<<" is yptr \n"<<*yptr<<"\t is *yptr\n"; //Displaying what is at yptr and at *yptr
cout<<"Give value to store at pointer zptr "; //Asking to give value to store at zptr address, say an integer 10.
cin>>*zptr;
//Taking value to store at zptr address, say an integer 10
cout<<"\nThe value provided for pointer zptr is "<<*zptr; //Displaying output
getche(); //Used to get a key from user then end the program,
//as the program will run too quick to see.
}
This one is giving run-time error, while displaying output of zptr, I mean at the end, I moved the zptr statements above but no use same problem while giving output of zptr...............WHY, what is going on?
//This is a template I use to understand the concepts of c++
#include<iostream.h>
#include<stdlib.h>
#include<conio.h>
main()
{
int *zptr; //Declaring a pointer zptr (THE CHANGE OF LINE)int x,*yptr; //Declaring an integer x and pointer yptr
//Line moved up
x=3; //Assigning value to variable x
yptr=&x; //Storing address of variable x at pointer yptr
cout<<yptr<<" is yptr \n"<<*yptr<<"\t is *yptr\n"; //Displaying what is at yptr and at *yptr
cout<<"Give value to store at pointer zptr "; //Asking to give value to store at zptr address, say an integer 10.
cin>>*zptr;
//Taking value to store at zptr address, say an integer 10
cout<<"\nThe value provided for pointer zptr is "<<*zptr; //Displaying output
getche(); //Used to get a key from user then end the program,
//as the program will run too quick to see.
}
Your zptr is never set to point to any memory. It just points to some random piece of memory, and then when you write into that memory, you break something.
When you make a pointer, you have to point it to some memory yourself. zptr is a pointer to an int, but you never made the int that it points to.
You don't have that problem with yptr, because you actually point that to some memory with this line: yptr=&x; //Storing address of variable x at pointer yptr