【发布时间】:2020-03-19 16:24:23
【问题描述】:
嗯,我想改变我的结构的编写方式,目前我使用数组,我需要限制它的使用,但我想要一种方法来创建一个动态数组,它的大小是完成读取的大小,而不总是编辑数组值。
当前代码:
struct sr_flag {
int value_flag;
};
struct er_time {
int value_time;
};
struct se_option {
struct sr_flag flag[50];
struct er_time time[50];
};
struct read_funcs
struct se_option *option;
void (*option_func) (void);
...
}
struct read_funcs func_;
struct read_funcs *func;
int sr_flags(int i, int fg, int val) {
if(i < 0)
return 0;
return func->option[i].flag[fg].value_flag = val;
}
void option_func(void) {
struct se_option fnc;
fnc.option = malloc(500 * sizeof(*(fnc.option)));
}
void read_fnc() {
func = &func_;
func->option = NULL;
func->option_func = option_func;
}
我寻找一种方法来删除数组数量 [50],而不是每次执行 sr_flags 函数时都会提高限制
示例:sr_flags 函数执行 1x 如果执行 2x[1] /strong> 将是 [2]
我也考虑用 option_func 函数做同样的事情
我尝试使用以下更不成功
struct se_option {
struct sr_flag *flag;
struct er_time time[50];
};
int sr_flags(int i, int fg, int val) {
if(i < 0)
return 0;
func->option[i].flag = malloc(1 * sizeof(*(func->option[i].flag)));
return func->option[i].flag[fg].value_flag = val;
}
int main () {
for(int i < 0; i < 10; i++)
sr_flags(i, 1, 30);
return 0;
}
【问题讨论】:
-
您是否尝试将数组的大小每次迭代增加 1?
-
@Nina 是的,就是这样
-
你能提供一个最小的可重现的例子吗? stackoverflow.com/help/minimal-reproducible-example
-
@Nina 我举了一个例子来说明我想要它的样子。
-
看看我编辑的答案。
标签: c memory dynamic-memory-allocation allocation