C结构中的数据丢失
材料h 结构单元{ int优先; int秒; }; 结构垫{ 结构细胞[行][COLS]; }; buf.hC结构中的数据丢失,c,function,pointers,buffer,C,Function,Pointers,Buffer,材料h 结构单元{ int优先; int秒; }; 结构垫{ 结构细胞[行][COLS]; }; buf.h struct-act{ 无效(*fct)(); }; 结构q{ int头; int top; 整数大小; 结构法案[]; }; buf.c void添加(结构q*b,void(*o)(){ b->actions[b->top].fct=o; b->top++; 如果(b->top==b->size)b->top=0; } Main.c int main(int argc,char*
struct-act{
无效(*fct)();
};
结构q{
int头;
int top;
整数大小;
结构法案[];
};
buf.c
void添加(结构q*b,void(*o)(){
b->actions[b->top].fct=o;
b->top++;
如果(b->top==b->size)b->top=0;
}
Main.c
int main(int argc,char**argv){
结构qb;
结构材料m;
添加(&b,初始化);
获取(&b,&m);
}
材料c
void init(结构q*b,结构mat*m){
srand(时间(空));
对于(int i=0;icells[i][j].first=rand()%5;
m->cells[i][j].second=rand()%2;
}
}
addQueue(b,printM);
}
嗨
在结构数组中添加函数指针时,会丢失该数组中的数据。我有一个缓冲区,它有一个void函数指针。使用add函数,我添加函数地址并在main.c上执行它。但问题是,每次我添加新函数时,都会有一个单元格丢失其数据(m.cells[0][3]。首先)。我不知道如何避免它
谢谢。类型为
struct q
的变量没有空间存储灵活数组成员操作的任何元素。为了发挥作用,struct q
需要成为更大内存块的一部分,其末尾有足够的空间容纳所需的元素数量
您可以创建一个函数,以便从动态分配的存储中分配结构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;
}
struct q
类型的变量没有空间存储灵活数组成员的任何元素actions
。为了发挥作用,struct q
需要成为更大内存块的一部分,其末尾有足够的空间容纳所需的元素数量
您可以创建一个函数,以便从动态分配的存储中分配结构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;
}
这里有一个灵活的数组成员。这个东西需要显式分配。struct q
的最后一个成员是所谓的灵活数组成员,数组类型不完整。struct q
的大小等于但不包括灵活数组成员的大小。struct q
需要嵌入到内存块中(例如,由malloc
或realloc
分配),并在末尾为数组内容留出足够的空间。例如,一块大小为offsetof(struct q,fct[10])
的(适当对齐的)内存可以容纳10个元素。纠正我之前的评论,我应该写offsetof(struct q,act[10])
(或者offsetof(struct q,actions[10])
,这取决于你发布的代码的哪一部分是可信的)。您有一个灵活的数组成员。这个东西需要显式分配。struct q
的最后一个成员是所谓的灵活数组成员,数组类型不完整。struct q
的大小等于但不包括灵活数组成员的大小。struct q
需要嵌入到内存块中(例如,由malloc
或realloc
分配),并在末尾为数组内容留出足够的空间。例如,一块大小为offsetof(struct q,fct[10])
的(适当对齐的)内存可以容纳10个元素。纠正我之前的评论,我应该写offsetof(struct q,act[10])
(或者offsetof(struct q,actions[10])
,这取决于你发布的代码的哪一部分是可信的)。