954,504 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Help with a pointers and memory assignment

Hi,

I've got an assignment at school that I would really like help with. I'm a total newbie.

#include <iostream>
using namespace std;
int main()
{
	char chr=(char)67;
	unsigned int offset = 1000;
	char * ptr=(char*)0;
	ptr+=offset;
	cout
	 << ptr[0]
	 << (char)43
	 << (char)(chr-24)
	 << endl;
}


The questions I'm gonna answer is:

1. Compile and run the program. What's happening? Can you explain why?

2. In the program, it's defined an integer like this: unsigned int offset = 1000;

By changing the line to unsigned int offset =(unsigned int)&chr;

the program will work. Please explain what the new line does, and why it makes the program work.

3. Write a shorter program that gives the same output as when the program works.

4. Explain what happens, line for line in the program.

Would really appreciate some help!

geir88
Newbie Poster
2 posts since Apr 2011
Reputation Points: 10
Solved Threads: 0
 

It looks like a demonstration of arrays as pointers in conjunction with a demonstration of pointer arithmetic. The version that works is a convoluted way of assigning the reference (address) of chr to ptr.

Fbody
Posting Maven
2,930 posts since Oct 2009
Reputation Points: 833
Solved Threads: 393
 

Thank you for answering.
But can you explain why a segmentation fault is occuring when the program is run with offset = 1000?

geir88
Newbie Poster
2 posts since Apr 2011
Reputation Points: 10
Solved Threads: 0
 

Seg faults are caused when your program accesses (and potentially corrupts) portions of your system's memory that are not assigned to it. Odds are address 1000 is not an address assigned to your program.

Thus, for the first version of your program, that is not an unexpected result.

Fbody
Posting Maven
2,930 posts since Oct 2009
Reputation Points: 833
Solved Threads: 393
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: