Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Memory Allocation

Name: Anonymous 2009-10-08 11:02

Hey /prog/riders,

I'm fairly new to C, I'm working with a piece of code that reads from a file to populate an array. My problem is the size of the array is not static, and I have no idea how large the end result is going to be.

Here's something I hacked up for an example, I haven't started working on the piece of code yet, I'm just wondering how I should handle the memory allocation for stct.


struct strct{
    bool b;
    char c;
}stct*;

int stct_length, stct_height, x, y;

char s[1024];
file = fopen(path, "rb");

for(y = 0;!feof(file);++y){
    fscanf(file, "%s", &s);
    for(x = 0;;++x){
        t = y * stct_length + x;
        switch(s[x]){
            case '0':
                stct[y * stct_length + x].b = 0;
                stct[y * stct_length + x].c = 'd';
                continue;
            case '1':
                stct[y * stct_length + x].b = 1;
                stct[y * stct_length + x].c = 'f';
                continue;
            case '\n':
                break;
        }
        break;
    }
    if(y == 0){
        stct_length = x;
    }
    else if(x != stct_length){
        printf("line %d is of irregular length", y)
        break;
    }
}

stct_height = y;

Name: Anonymous 2009-10-08 11:39

>>5
You can realloc your data, but that can be costly. Other people may prefer doubling the buffer's capacity by 2 each time you hit it, which would be less costly than reallocing each time, while others prefer using some form of linked list. Linked lists are probably the nicest way to deal with it, but it's less comfortable to work with them in C than in more high-level languages(most high-level language make it trivial enough, but Lisp likely offers the easiest way to manage lists - so easy that I've even seen people greenspun Lisp's list handling functions in C). There's some other aproaches, but they usually end up being similar to the previous two, or a combination of them.

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List