12.4: Using Memory

Embedded Controllers Using C and Arduino · LibreTexts

0%

Contents

    Text

    Size
    100%
    Theme
    Typeface
    Line length
    Spacing

    From LibreTexts, under CC BY-NC-SA 4.0, as the source states it; its equations are written in TeX, which the PDF shows typeset. This page at LibreTexts.

    12.4: Using Memory

    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 );
    }
    

    This page titled 12.4: Using Memory was last modified on Wed, 08 Sep 2021 02:57:31 GMT and is shared under a CC BY-NC-SA 4.0 license and was authored, remixed, and/or curated by James M. Fiore via source content that was edited to the style and standards of the LibreTexts platform.