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[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!

5 Years
Discussion Span
Last Post by Fbody

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.

Edited by Fbody: n/a


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.

Edited by Fbody: n/a

This article has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.