Dynamic Memory and Pointers in C


C Programming with Al Jensen

One of the blessings (some would say curse) of C is the degree to which we are able to micromanage dynamic memory in C.  By allocating and deallocating memory dynamically our programs can execute with greater flexibility and efficiency. Liked lists and queues, for instance, would be impossible to implement without dynamic memory allocation. The use of pointers is integral to tracking dynamically allocated memory in C.

Dynamic memory allocation in C begins with the use of malloc() or a similar function to allocate memory. This memory is then used by the program via a pointer. Finally, we deallocate the memory use the free() function.

#include <stdio.h>
#include <stdlib.h>

int main(void){
    
    double *d = (double*)malloc(sizeof(double));
    int *i = (int*)malloc(sizeof(int));
    
    *i = 2600;
    *d = 5.11;

    printf("%dn", *i);
    printf("%fn", *d);

    return 0;
    
}

The malloc() function accepts an…

View original post 510 more words

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s