​A selection of topics on IT and its application to finance. 
​Send me your comments, questions ​or suggestions by clicking
h​ere


elmama
Implementing dynamic arrays in C 


Dynamic arrays are useful in situations where you want to read data into memory but you don't know in advance how big the data set will be. The usual way to do this kind of thing is to use linked lists but I find that dynamic arrays, although similar, are much easier to code. Below is a very simple example of reading in a code and description from an external file into memory.


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

FILE *fn;

struct look
{
        char code[4];
        char desc[70];
};

static struct look *lookup = 0;
int num_codes = 0;


int load_lookup();
void print_lookup();

main()
{

        fn = fopen("codes.dat","r");

        /* Read 'em in */

        if((num_codes= load_lookup()) <= 0)
                fprintf(stderr,"Error loading lookup data\n");
        /* print 'em out */
        print_lookup();
}

int load_lookup()
{
        static int code_count=0;
        int ret_val = 0;
        char lookup_code[4];
        char lookup_desc[70];

        while(1)
        {
                ret_val = fscanf(fn,"%s% %69c\n",lookup_code,lookup_desc);
                if(ret_val != 2)
                        break;

                code_count++;
                if((lookup=(look *)realloc(lookup,code_count*sizeof(struct look))) ==NULL)
                {
                        fprintf(stderr,"realloc failed\n");
                        return(-1);
                }


                strcpy(lookup[code_count-1].code,lookup_code);
                strcpy(lookup[code_count-1].desc,lookup_desc);
        }
        return(code_count);
}

void print_lookup()
{
        int i;
        for(i=0;i<num_codes;i++)
        {
                printf("%s %s\n",lookup[i].code,lookup[i].desc);
        }
}