2

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!

Dale Hagglund
  • 16,074
  • 4
  • 30
  • 37
Kitchi
  • 1,874
  • 4
  • 28
  • 46
  • 1
    What is reason for such array? – rkosegi Oct 26 '12 at 07:01
  • 1
    if you want an array of FILE* your code above will work. each FILE* can be indexed with `fptr[n]`. make damn sure to close all those when you're done and free() the block. I'm not gonna ask why you're doing this. that's *your* problem =) – WhozCraig Oct 26 '12 at 07:04
  • @rkosegi -I want to open several files at the same time. The files are sequentially numbered, so I thought I could loop through them to open them all at the same time. – Kitchi Oct 26 '12 at 07:04
  • Yes, you can. It's just an array of pointers. – John Szakmeister Oct 26 '12 at 07:04
  • 2
    There is no reason to [cast the result of calloc/malloc](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc). – Lundin Oct 26 '12 at 07:22

2 Answers2

2

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,

Dale Hagglund
  • 16,074
  • 4
  • 30
  • 37
  • This is cool... but my code seems to work for my case. Is this just another way of implementing the same thing? – Kitchi Oct 26 '12 at 08:49
  • Really weird to use `callloc()`, with a pointless clearing (and no chance of efficiently growing the block) instead of `realloc()` which would include the copying done next. – unwind Oct 26 '12 at 09:58
  • @unwind: Opinions vary on whether or not one should use `realloc`. It is the universal allocate/grow/shrink/free function, which perhaps is a bit much for one single entry point. That said, I wouldn't use `calloc` myself in code like this, I'd use `malloc` (or, maybe, `realloc`). – Dale Hagglund Oct 30 '12 at 09:23
  • Thanks to @JimBalter for some fixes. – Dale Hagglund Oct 30 '12 at 09:24
  • 1
    @Kitchi: at least in your post, I only see one assignment to `fptr`. How do you choose the `n` given to `calloc`? What happens if you end up needing more `FILE *` values than you originally allocated space for? In that case, you'll need to grow the array somehow, which will look something like the code I show here. – Dale Hagglund Oct 30 '12 at 09:26
1

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

Omkant
  • 9,018
  • 8
  • 39
  • 59