0
嗨,這裏是我的代碼。我想dynamincly變化沒有在表結構elemnts的__state:C結構表動態內存分配
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]
到SMTH像st+ptr
?指針在每個循環迭代中佔據什麼位置?或者我錯了?當我更改代碼:初始化爲state_p st[20]
,並在每個循環迭代中,我把st[i] = (state_p)malloc(sizeof(state_t))
一切工作正常,但我想動態地更改該表中的元素數。
提前THX任何幫助
什麼是函數原型了save_state()? – 2010-05-27 15:25:11
雖然它與你的問題沒有關係,但你應該認識到'__state'這個名字是爲實現保留的,所以你不應該使用它。 – 2010-05-27 15:38:33
這裏是: (對不起,我不知道如何把'代碼標記'在這裏) void save_state(state_p st,int previous_state,int state){ st-> timestamp = 0; st-> prev_value = previous_state; st-> val = state; } – JosiP 2010-05-27 15:44:01