Sign in to follow this  

Basic Pointer Problems

Recommended Posts

I'll start by posting the code. I'm not sure how to use the source tags so I may need to fix this.

#include <iostream.h>

// int number = 0;

// In this function I am looking at all of the aspects of pointers.  You might recognize some of these from the tutorial on Gamedev.

void Pointer_Test()
	int a = 10;
	int b = 20;
 	int *pa, *pb;
	pa = &a;
	pb = &b;

	cout << "A = " << a << endl;
        cout << "B = " << b << endl;
        cout << "pA = " << pa << endl;
        cout << "pB = " << pb << endl;
        cout << "&A = " << &a << endl;
        cout << "&B = " << &b << endl;
        cout << "pA + 1 = " << ++pa << endl;
        cout << endl << endl << endl;
(*pa) = 25;

//At this point the program crashes with the error "The value of ESP was not properly saved across a function call.  This is usually the result of calling a function declared.."
// A search on the internet wasn't very helpful, and simply removing the "(*pa) = 25;" line will remove the error.

cout << "pA =  " << pa << endl;
cout << "A =  " << a << endl;

//But if I use this function then there is no problem and no error.  I don't see the difference between the way I am calling the *pa pointer, and the *pointer_to_hello.  

void Next()
	int hello = 0;
	cout << "Hello = " << hello << endl;

	int* pointer_to_hello = &hello;
	cout << "pointer_to_hello = " << *pointer_to_hello << endl;

	(*pointer_to_hello) = 25;
        cout << "Hello = " << hello << endl;
	cout << "pointer_to_hello = " << pointer_to_hello << endl;

int main()



		  return 0;
I already checked on the internet but I wasn't able to find anything that explained the problem simply.

Share this post

Link to post
Share on other sites
Original post by Vices
<snip />#include <iostream.h><snip />

Hasn't been right since 1998. It's <iostream>, no ".h". You'll also need to add std:: to your cout and endls, or using std::cout; and using std::endl; or using namespace std;
Original post by Vices
<snip />cout << "pA + 1 = " << ++pa << endl;<snip />

You've incremented pa which means it no longer points at what it used to. It now points to some random* (invalid) memory location, causing a crash when you try to write to it.

*I say random. It's actually well defined, it's sizeof(int) bytes past a in memory. It's only random in the sense that you have no idea what, if anything, exists at that memory location.


Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this