C 结构数组的奇怪行为
我有这样的结构:C 结构数组的奇怪行为,c,arrays,struct,C,Arrays,Struct,我有这样的结构: typedef struct { // ... other names size_t size; // size of frame } frame_index_t; typedef struct { // ... other names size_t frames_read; // number of read frames size_t frames_size; // size of frames ar
typedef struct {
// ... other names
size_t size; // size of frame
} frame_index_t;
typedef struct {
// ... other names
size_t frames_read; // number of read frames
size_t frames_size; // size of frames array
frame_index_t *frames; // array of indexed frames
} state_t;
这是附加到数组中:
// ... state allocated earlier
state->frames_size = 0;
state->frames_read = 0;
while (...) {
if (state->frames_read == state->frames_size) {
state->frames_size += FRAMES_CHUNK_SIZE; // += 100
state->frames = realloc(
state->frames,
state->frames_size * sizeof(frame_index_t)
);
if (!state->frames) {
goto error;
}
}
state->frames[state->frames_read].size = calculated_frame_size;
state->frames_read++;
}
state->frames_size = state->frames_read;
state->frames_read = 0;
后来我读了frames数组:
while (...) {
printf(
"Frame %lu of %lu\n",
state->frames_read,
state->frames_size
);
if (state->frames[state->frames_read].size == 0) {
printf("Frame %lu is zero size\n", state->frames_read);
} else if (state->frames[state->frames_read].size > 2000) {
printf(
"Frame %lu is %lu bytes",
state->frames[state->frames_read].size
);
}
state->frames_read += 1;
}
我有以下输出:
Frame 2684 of 11737
Frame 2685 of 11737
Frame 3344 is 0 bytes
Frame 2686 of 11737
Frame 2687 of 11737
Frame 2688 of 11737
Frame 2689 of 11737
Frame 2690 of 11737
Frame 2691 of 11737
Frame 2692 of 11737
Frame 4033 is 0 bytes
Frame 2693 of 11737
Frame 2694 of 11737
哇!怎么了?我误解了。
是否会影响分配的其他资源?它们能相交吗?瓦尔格林对此只字未提。没有内存泄漏,没有读取错误。@user3121023谢谢!我现在非常不专心,显然我得去sleep@user3121023这一点不重要,仅用于测试,dirtyIn state->frames[state->frames\u read].size=computed\u frames\u size;是基于状态->帧的还是基于1的。如果基于1,则索引错误。@WeatherVane基于0