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'."
#include <iostream>
#include <iomanip>
usingnamespace 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.
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
<< 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.