PRODUCT : Borland C++ NUMBER : 1705 VERSION : 3.X OS : DOS OS/2 DATE : October 25, 1993 PAGE : 1/2 TITLE : User implemented memory management /* TESTPARY.CPP: User implemented memory management The following example allocates a block of memory, creates an array of offsets at the start of this memory and installs an arrays of strings to which these offsets point. No compiler generated arrays are specified. The offsets are relative to the start of the allocated block of memory, i.e., 'string' location = 'startOfMemoryBlock'+'offset'. After initializing the memory allocation, this example calls a function which displays the strings. DEMONSTRATES: - use of ostrstream with user supplied buffer - use of casting operations to control pointer math - use of user managed arrays NOTES: (1) Tested with BC++ for OS/2 1.0 and BC++ for DOS 3.1 */ #include #include void testPass(short *t) { short i=0; char *tt = ((char*)(unsigned int)t+(short)t[i]); // Array is terminated by a -1 (0xffff). while (t[i] != -1) { cout << endl << tt; // 't' must be cast to 'int' so that the compiler operates // on its address. The sum is cast to char* so that the // iostream machinery will display a string rather than an // address. The whole expression is enclosed in parens to // resolve the precedence ambiguity between the summation // operator and the insertion operator. tt = ((char*)(unsigned int)t+(short)t[++i]); } } //************************************************************** int main(void) { PRODUCT : Borland C++ NUMBER : 1705 VERSION : 3.X OS : DOS OS/2 DATE : October 25, 1993 PAGE : 2/2 TITLE : User implemented memory management // Give us 1000 bytes (sizeof(short)*500) of heap. short *newMemory = new short[500]; if (!newMemory) { cout << "\nError"; return 1; } // Initialize 1st 20 bytes with 10 shorts; These 10 shorts // represent offsets from the start of 'newMemory' to // data stored later in 'newMemory'. Each item is a maximum // of 20 bytes long and the first item starts at location // 'newMemory'+0x300. for (int i=0; i<10; i++) { // Stuff offset into 'i'th offset array slot. newMemory[i] = (unsigned short)(0x300+(i*20)); // Create a string pointer to the 'i'th data item and... char *slot = (char*)newMemory+newMemory[i]; // ...setup an ostrstream object using that location. ostrstream aslot(slot, 20); // Now compose a string into that location. aslot << "string" << i << ends; } newMemory[i] = 0x0ffff; // Using the 10 offsets, display the strings. testPass(newMemory); return 0; } // end of main() DISCLAIMER: You have the right to use this technical information subject to the terms of the No-Nonsense License Statement that you received with the Borland product to which this information pertains.