Using pointer data types in C and C++ applications that use SQL

You can also declare host variables that are pointers to the supported C and C++ data types, with the following restrictions.

  • If a host variable is declared as a pointer, then that host variable must be declared with asterisks followed by a host variable. The following examples are all valid:
    short *mynum;                 /* Ptr to an integer                       */
    long **mynumptr;              /* Ptr to a ptr to a long integer          */
    char *mychar;                 /* Ptr to a single character               */
    char(*mychara)[20];            /* Ptr to a char array of 20 bytes         */
    struct {                      /* Ptr to a variable char array of 30      */
       short mylen;               /*     bytes.                              */
       char mydata[30];
      } *myvarchar;
     
    Note: Parentheses are only allowed when declaring a pointer to a NUL-terminated character array, in which case they are required. If the parentheses were not used, you would be declaring an array of pointers rather than the desired pointer to an array. For example:
    char (*a)[10];         /* pointer to a null-terminated char array */
    char *a[10];           /* pointer to an array of pointers         */
     
  • If a host variable is declared as a pointer, then no other host variable can be declared with that same name within the same source file. For example, the second declaration below would be invalid:
    char *mychar;                /* This declaration is valid               */
    char mychar;                 /* But this one is invalid                 */
     
  • When a host variable is referenced within an SQL statement, that host variable must be referenced exactly as declared, with the exception of pointers to NUL-terminated character arrays. For example, the following declaration required parentheses:
    char (*mychara)[20];         /* ptr to char array of 20 bytes           */

    However, the parentheses are not allowed when the host variable is referenced in an SQL statement, such as a SELECT:

    EXEC SQL SELECT name INTO  :*mychara FROM mytable;
  • Only the asterisk can be used as an operator over a host variable name.
  • The maximum length of a host variable name is affected by the number of asterisks specified, as these asterisks are considered part of the name.
  • Pointers to structures are not usable as host variables except for variable character structures. Also, pointer fields in structures are not usable as host variables.
  • SQL requires that all specified storage for based host variables be allocated. If the storage is not allocated, unpredictable results can occur.