home *** CD-ROM | disk | FTP | other *** search
/ Microsoft Programmer's Library 1.3 / Microsoft-Programers-Library-v1.3.iso / sampcode / win_lrn / memory / local / loclallo.c < prev    next >
Encoding:
C/C++ Source or Header  |  1988-08-11  |  1.7 KB  |  62 lines

  1. /*
  2.  *   LocalAlloc
  3.  *
  4.  *   This program demonstrates the use of the LocalAlloc function.
  5.  *   The LocalAlloc function allocates space for use in the local heap.
  6.  */
  7.  
  8. #include <windows.h>
  9.  
  10. int sprintf();
  11.  
  12. typedef struct {        /* structure we are going */
  13.         int x;        /* to allocate and lock   */
  14.         int y;
  15.            } MYSTRUCT;
  16.  
  17. typedef MYSTRUCT *lpMyPtr;  /* far pointer to MYSTRUCT type */
  18.  
  19. int PASCAL WinMain( hInstance, hPrevInstance, lpszCmdLine, cmdShow )
  20. HANDLE hInstance, hPrevInstance;
  21. LPSTR lpszCmdLine;
  22. int cmdShow;
  23. {
  24.     HANDLE hMemBlock;      /* Handle to memory block         */
  25.     lpMyPtr  ThisPtr;      /* Pointer to MYSTRUCT structure   */
  26.     char szBuff[80];      /* buffer for message box         */
  27.  
  28. /* allocate space in global heap for a MYSTRUCT structure */
  29.     hMemBlock = LocalAlloc(GMEM_ZEROINIT | GMEM_MOVEABLE,
  30.             (long)sizeof(MYSTRUCT));
  31.  
  32. /* if memory allocated properly */
  33.     if (hMemBlock != NULL)
  34.     {
  35.     MessageBox(NULL,(LPSTR)"The memory was allocated properly",
  36.             (LPSTR)" ",MB_OK);
  37.  
  38.     /* lock memory into current address */
  39.     ThisPtr = (lpMyPtr)LocalLock(hMemBlock);
  40.  
  41.     /* if lock worked */
  42.     if (ThisPtr != NULL)
  43.         {
  44.         /* use memory from global heap and output results*/
  45.         ThisPtr->x = 4;
  46.         ThisPtr->y = 4;
  47.         ThisPtr->x = ThisPtr->x*ThisPtr->y;
  48.         sprintf(szBuff,"ThisPtr->x * ThisPtr->y = %d",ThisPtr->x);
  49.         MessageBox(NULL,(LPSTR)szBuff,
  50.                 (LPSTR)"Info from LocalAlloc'ed memory",
  51.                 MB_OK);
  52.         LocalUnlock(hMemBlock);    /* unlock block */
  53.         LocalFree(hMemBlock);      /* free block   */
  54.         }
  55.     else ;
  56.     }
  57.     else
  58.     MessageBox(NULL,(LPSTR)"The memory was not allocated",
  59.             (LPSTR)" ",MB_OK);
  60.     return 0;
  61. }
  62.