Three Pointers and One Piece of Memory

I posted this previously but accidentally deleted it. Im working through a book exercise that reads this, "using one piece of memory. store a long integer, four characters, and a float. Put the first four letters of your first name in the four characters. Second, subtract a number from either the long integer or the float to change the fourth character to an 'A' or 'a'."

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <iomanip>
using namespace std;

/////////////////////
//using three pointers, point to the same piece of memory
//and subtract from either the int or the float to change
//the last letter into an 'A' or 'a'
//////////////////////
void char_manip();

int main(){
	long longInt = 1;
	long *longPtr = &longInt;
	char *charPtr = &longInt;
	float *floatPtr = &longInt;
	
	cout << "longPtr is in address " << longPtr << " and points to the value " << *longPtr << endl
         << "charPtr is in address " << charPtr << "and points to the value " << *charPtr << endl
	     << "floatPtr is in address " << floatPtr << " and points to the value " << *floatPtr << endl;
		 
	return 0;
}


Obviously what I have is completely incorrect as I really don't know how to continue on this one. Any reading suggestions or other tips would be greatly appreciated.
Exercise that makes use of undefined behaviour :/
Last edited on
char *charPtr = &longInt;

Here you are trying to set a char* to be the same as a long*. That won't work. You have to cast the long* into a char* first.

Try:
char *charPtr = (char*)&longInt;

Similarly with float *floatPtr = &longInt;
Any ideas? The book is called "C++ Pointers and Dynamic Memory Management". This is the first exercise, and the book states that anyone who has completed a intro to C++ course can complete this book.
Thank you for the casting advice. It worded perfectly.

1
2
3
4
long longInt = 1;
	long *longPtr = &longInt;
	char *charPtr = (char*)&longInt;
	float *floatPtr = (float*)&longInt;


when it prints to screen, it shows this..

longPtr is in address 0xbfd26e9c and points to the value 1
charPtr is in address and points to the value 
floatPtr is in address 0xbfd26e9c and points to the value 1.4013e-45

why is charPtr not have an address?
<< is overloaded for objects of type char*. It will dereference it. If you want to know the actual value of the pointer, you will have to cast it to something else first.

Try this:

...<< "charPtr is in address " << (int*)charPtr << " and points to the value " << charPtr << endl...
Thanks Moschops. Is this where a person might use a void*? Because I did just read something about printing out a char pointer assumes your printing a string.
Topic archived. No new replies allowed.