Public Group

# Basic Pointer Problems

This topic is 4239 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## 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.
[Source]

#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()
{

//Next();

Pointer_Test();

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

##### Share on other sites
Quote:
 Original post by Vices#include

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;
Quote:
 Original post by Vicescout << "pA + 1 = " << ++pa << endl;

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.

Σnigma

##### Share on other sites
Ohh, thank you :)

1. 1
2. 2
3. 3
Rutin
22
4. 4
JoeJ
16
5. 5

• 14
• 29
• 13
• 11
• 11
• ### Forum Statistics

• Total Topics
631774
• Total Posts
3002292
×