Skip to main content
Engineering LibreTexts

12.4: Using Memory

  • Page ID
  • The pointer that is returned from the allocation function is used as the base of the object or array of objects in which you’re interested. Keeping it simple, suppose you want to allocate an array of three integers. If you want to set the first element to 0, and the second and third elements to 1, do the following (code fragment only, error processing not shown):

    int *ip;
    if( ip = calloc( 3, sizeof(int) ) )
        *ip = 0;
        *(ip+1) = 1;    /* could also say ip[1] = 1; */
        *(ip+2) = 1;    /* could also say ip[2] = 1; */

    Note the freedom that we have with the pointer. It can be used as a normal pointer or thought of as the base of an array and indexed accordingly. Similarly, we might need to allocate a structure and initialize its fields. Here is a function that we can call to allocate a struct foobar, initialize some fields, and return a pointer to it.

    struct foobar {
        double d;
        int i;
        char name[20];
    /* other code... */
    struct foobar * alloc_foobar( void )
        struct foobar *fp;
        if( fp = malloc( sizeof(struct foobar) ) )
            fp->d = 12.0; /* just some stuff to show how... */
            fp->i = 17;
            strcpy( fp->name, “Timmy” );
        return( fp );