gpt4 book ai didi

c - 如何在C中定义可变参数

转载 作者:行者123 更新时间:2023-11-30 19:15:42 27 4
gpt4 key购买 nike

有没有办法在 C 中定义可变大小变量?

例如,我想定义一个表,表中的条目和每个条目的大小都应根据配置文件的变化而变化,而无需重新编译源代码。

要动态定义表的条目,我们可以使用C中的malloc或C++中的new,但是大小是多少?我的意思是像下面这样

typedef union {
// the size of x is determined by the configuration file
typeof(x) x;
struct {
// n, m are read from the configuration file when the program is running
typeof(x1) x1: n;
typeof(x2) x2: m;
// Also, the fields should be variadic
... //other_variable
};
};

非常感谢您,即使您认为很荒谬,也请回复我。

最佳答案

C 不管理可变大小类型定义。您必须通过指针和内存分配(例如 mallocnew)自行管理它。

这就是许多程序存在内存泄漏的原因之一......

unsigned int n,m;   // n, m are read from the configuration file when the program is running

struct x {
x1_t * x1;
x2_t * x2;
... //other_variables
};

int xread(struct x *decoded, const char *datap, int size)
{
malloc(x->x1, m);
if (!x->x1)
return -1;
malloc(x->x2, n);
if (!x->x2) {
free(x->x1);
return -1;
}
memcpy(x->x1, datap, m);
memcpy(x->x2, datap+m, n);
... // other_variables
return m+n;//+...
}

int xwrite(char *bufferp, const struct x *decoded)
{
// bufferp shall be allocated with at least m+n
if (x->x1) {
memcpy(bufferp, x->x1, m);
bufferp += m;
}
if (x->x2) {
memcpy(bufferp, x->x2, n);
bufferp += n;
}
... // other_variables
}

关于c - 如何在C中定义可变参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32055078/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com