Question

is it possible to 'dynamically' allocate file pointers in C? What I mean is this :

FILE **fptr;
fptr = (FILE **)calloc(n, sizeof(FILE*));

where n is an integer value. I need an array of pointer values, but I don't know how many before I get a user-input, so I can't hard-code it in. Any help would be wonderful!

Was it helpful?

Solution

You're trying to implement what's sometimes called a flexible array (or flex array), that is, an array that changes size dynamically over the life of the program.) Such an entity doesn't exist among in C's native type system, so you have to implement it yourself. In the following, I'll assume that T is the type of element in the array, since the idea doesn't have anything to do with any specific type of content. (In your case, T is FILE *.)

More or less, you want a struct that looks like this:

struct flexarray {
    T *array;
    int size;
}

and a family of functions to initialize and manipulate this structure. First, let's look at the basic accessors:

T  fa_get(struct flexarray *fa, int i) { return fa->array[i]; }
void fa_set(struct flexarray *fa, int i, T p) { fa->array[i] = p; }
int fa_size(struct flexarray *fa) { return fa->size; }

Note that in the interests of brevity these functions don't do any error checking. In real life, you should add bounds-checking to fa_get and fa_set. These functions assume that the flexarray is already initialized, but don't show how to do that:

void fa_init(struct flexarray *fa) {
    fa->array = NULL;
    fa->size = 0;
}

Note that this starts out the flexarray as empty. It's common to make such an initializer create an array of a fixed minimum size, but starting at size zero makes sure you exercise your array growth code (shown below) and costs almost nothing in most practical circumstances.

And finally, how do you make a flexarray bigger? It's actually very simple:

void fa_grow(struct flexarray *fa) {
    int newsize = (fa->size + 1) * 2;
    T *newarray = malloc(newsize * sizeof(T));
    if (!newarray) {
        // handle error
        return;
    }
    memcpy(newaray, fa->array, fa->size * sizeof(T));
    free(fa->array);
    fa->array = newarray;
    fa->size = newsize;
}

Note that the new elements in the flexarray are uninitialized, so you should arrange to store something to each new index i before fetching from it.

Growing flexarrays by some constant multiplier each time is generally speaking a good idea. If instead you increase it's size by a constant increment, you spend quadratic time copying elements of the array around.

I haven't showed the code to shrink an array, but it's very similar to the growth code,

OTHER TIPS

Any way it's just pointers so you can allocate memory for them but don't forget to fclose() each file pointer and then free() the memory

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top