[英]C loss data in structure
mat.h数学
struct cell {
int first;
int second;
};
struct mat {
struct cell cells[ROWS][COLS];
};
buf.h缓冲区
struct act {
void (*fct)();
};
struct q {
int head;
int top;
int size;
struct act act[];
};
buf.c buf.c
void add(struct q *b, void (*o)()) {
b->actions[b->top].fct = o;
b->top++;
if(b->top == b->size) b->top = 0;
}
Main.c主.c
int main(int argc, char **argv) {
struct q b;
struct mat m;
add(&b, init);
get(&b, &m);
}
mat.c垫子.c
void init(struct q *b, struct mat *m) {
srand(time(NULL));
for(int i = 0; i < ROWS; i++) {
for(int j = 0; j < COLS; j++) {
m->cells[i][j].first = rand() %5;
m->cells[i][j].second = rand() %2;
}
}
addQueue(b, printM);
}
Hi,你好,
I lose data in a structure array when I add function pointer on it.当我在结构数组上添加 function 指针时,我会丢失结构数组中的数据。 I have a buffer which has a void function pointer.
我有一个缓冲区,它有一个 void function 指针。 With add function, I add the function address and execute it on main.c.
通过添加 function,我添加 function 地址并在 main.c 上执行。 But the problem is, every time I add a new function, there is a cell loses its data (m.cells[0][3].first).
但问题是,每次我添加一个新的 function 时,都会有一个单元格丢失其数据(m.cells[0][3].first)。 I did not find how to avoit it.
我没有找到如何避免它。
Thanks.谢谢。
A variable of type struct q
has no room to store any elements of the flexible array member actions
. struct q
类型的变量没有空间来存储灵活数组成员actions
的任何元素。 In order to be useful, the struct q
needs to part of a larger block of memory with enough room at the end for the number of required elements.为了有用,
struct q
需要成为 memory 更大块的一部分,并在末尾有足够的空间容纳所需元素的数量。
You could create a function to allocate a struct q
from dynamically allocated storage with enough space for a specified number of elements:您可以创建一个 function 从动态分配的存储中分配一个
struct q
,并为指定数量的元素提供足够的空间:
#include <stddef.h>
#include <stdlib.h>
struct q *create_q(int size) {
struct q *b = malloc(offsetof(struct q, actions[size]));
if (b) {
b->head = 0;
b->top = 0;
b->size = size;
}
return b;
}
For consistency, a function can be added to free the struct q
.为了保持一致性,可以添加 function 以释放
struct q
。 That is pretty simple now, but having a specific function allows the internals of the implementation to be changed at a later time if need be:现在这很简单,但是拥有一个特定的 function 可以在以后根据需要更改实现的内部结构:
void free_q(struct q *b) {
free(b);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.