繁体   English   中英

结构表的C动态内存分配

[英]C dynamic memory allocation for table of 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;
}

我想我必须将st[i]更改为st+ptr吗? 每次循环迭代中指针在哪里固定? 还是我错了? 当我更改代码时:初始化为state_p st[20]并在每次循环迭代中我将st[i] = (state_p)malloc(sizeof(state_t))都工作正常,但我想动态地更改该表中的元素数。

事先感谢任何帮助

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

save_state(st + i, previous_state, state);

要么

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM