// Filename : JellyB1.CPP
// Demonstration of pointer scope issues
//
#include <iostream.h>
#include <string.h>
struct JellyBean
{
int i;
int j;
char* str;
};
void main()
{
JellyBean red = {1,2,0};
red.str = new char[30];
strcpy(red.str,"A red jelly bean");
JellyBean anotherRed = red;
// But now both red.str and anotherRed
// point to str
cout << anotherRed.i << ", "
<< anotherRed.j << ", "
<< anotherRed.str;
strcpy(red.str,"A blue jelly bean");
// Is this a surprise?
cout << endl << "After assignment to red:" << endl;
cout << anotherRed.i << ", "
<< anotherRed.j << ", "
<< anotherRed.str;
delete [] red.str;
red.str = 0; // Good practise
// What does anotherRed.str equal?
//
// Another small experiement
//
{
char newString[] = "Oh! no! not the comfy chair! ";
red.str = newString;
} // newString no longer exists
{
char anotherNewString[] = "No one expects the Spanish Inquisition!";
cout << endl << red.str; // red.str should point to newString???
}
}
Tidak ada komentar:
Posting Komentar