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:23

>>1
malloc if you plan on writing to the entire buffer, or don't care that it might contain random data.
calloc if you need a zero'ed out buffer, it's also considered nicer as it lets you separate the amount of items and each item size's, instead of writing data=malloc(count*sizeof(SOMETHING));memset(data,0,count*sizeof(SOMETHING));

Don't forget to free your buffer once you're done with it.

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