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!

Recommended Answers

All 3 Replies

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.

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

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.