我有以下結構:malloc的陣列,在字段中的數據不保存正確
struct message {
int id;
int ack;
int data_len;
char *data;
time_t timer;
} *messages, *temp;
我分配這些結構的一塊內存來保存高達numMessages量:
messages = malloc(sizeof(messages)*numMessages);
然後ñ消息可以通過調用函數ReadFromFile(INT)被添加,以初始化爲0
計數void readFromFile(int n) {
char input_buff[4096];
int size = sizeof(struct message);
for (int i = 0; i < n; i++) {
bzero(input_buff, sizeof(input_buff));
int nread = fread(input_buff, 1 , msgSize, fp);
if (nread > 0) {
printf("adding message: %d\n", count);
temp = (struct message *) malloc (sizeof (struct message));
temp->data_len = nread;
temp->id = count; // set integer id
temp->data = malloc(sizeof(char) * (nread));
temp->ack = 0;
memcpy(temp->data, input_buff, nread);
memcpy(&messages[count],temp,sizeof(temp));
count++;
free(temp);
}
if (nread < sizeof(input_buff)) {
if (feof(fp))
printf("End of file\n");
free(filename);
close(fp);
break;
}
if (ferror(fp)) {
printf("Error reading\n");
break;
}
}
}
但是消息[count] .data沒有被存儲。但是,如果我換行:
temp->data_len = nread;
和
temp->data = malloc(sizeof(char) * (nread));
的數據存放不當,但現在DATA_LEN沒有存儲?我究竟做錯了什麼?除了事實,我敢肯定,有一個指針溫度和應付內存是多餘的...
謝謝!
[不投射的malloc的結果](http://stackoverflow.com/問題/ 605845/do-i-cast-of-malloc) – Barmar
'memcpy(&messages [count],temp,sizeof(temp));'也應該是'sizeof(* temp)' – immibis
「以下結構:「 - 不!你有指向'struct' – Olaf