C dynamic memory allocation for table of structs

Posted by JosiP on Stack Overflow See other posts from Stack Overflow or by JosiP
Published on 2010-05-27T15:22:40Z Indexed on 2010/05/27 15:51 UTC
Read the original article Hit count: 299

Filed under:
|

Hi here is my code. I want to dynamincly change no of elemnts in table with structs __state:

typedef struct __state{
    long int timestamp;
    int val;
    int prev_value;
}*state_p, state_t;

int main(int argc, char **argv){
    int zm;
    int previous_state = 0;
    int state = 0;
    int i = 0;
    int j;
    state_p st;
    //here i want to have 20 structs st.
    st = (state_p) malloc(sizeof(state_t) * 20);
    while(1){
        previous_state = state;
        scanf("%d", &state);
        printf("%d, %d\n", state, previous_state);
        if (previous_state != state){
            printf("state changed %d %d\n", previous_state, state);
            // here i got compile error:
               main.c: In function ‘main’:
               main.c:30: error: incompatible type for argument 1 of ‘save_state’
               main.c:34: error: invalid type argument of ‘->’
               main.c:34: error: invalid type argument of ‘->’

            save_state(st[i],previous_state, state);
        }
        i++;
    }
return 0;
}

I suppose i have to change that st[i] to smth like st+ptr ? where pointer is incermeting in each loop iteration ? Or am I wrong ? When i change code: initialization into state_p st[20] and in each loop iteration i put st[i] = (state_p)malloc(sizeof(state_t)) everything works fine, but i want to dynammicly change number of elemets in that table.

Thx in advance for any help

© Stack Overflow or respective owner

Related posts about c

    Related posts about memory-allocation