结构表的C动态内存分配

时间:2010-05-27 15:22:41

标签: c memory-management

嗨,这是我的代码。我想用结构__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;
}

我想我必须将st[i]改为st+ptr?指针在每次循环迭代中的位置?还是我错了?当我改变代码时:初始化为state_p st[20]并且在每次循环迭代中我放置st[i] = (state_p)malloc(sizeof(state_t))一切正常,但我想动态地改变该表中的元素数量。

提前获取任何帮助

1 个答案:

答案 0 :(得分:2)

您没有显示save_state的原型。我假设第一个参数应该是指针到状态。如果是这种情况,那么您需要:

save_state(st + i, previous_state, state);

save_state(&(st[i]), previous_state, state);