を保存していない私は、次の構造体がありますのmallocアレイ、フィールドのデータが正しく
:struct message {
int id;
int ack;
int data_len;
char *data;
time_t timer;
} *messages, *temp;
を私は件までnumMessagesこれらの構造体の量を保持するためのメモリのチャンクを割り当てています
messages = malloc(sizeof(messages)*numMessages);
n 0に初期化されたReadFromFile(int)関数を呼び出してメッセージを追加することができます
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-the-mallocの結果) – Barmar
'memcpy(&messages [count]、temp、sizeof(temp));' 'sizeof(* temp) 'でなければなりません。 – immibis
"次の構造体: " - いいえ!あなたはその 'struct 'へのポインタを持っています – Olaf