簡體   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