gpt4 book ai didi

c - realloc() 结构数组的旧大小无效

转载 作者:行者123 更新时间:2023-11-30 16:13:14 25 4
gpt4 key购买 nike

我被指派为我们的学校辩护制定一个有效的学生选举计划(并且可能用于实际使用......)。然而,我已经被一个问题困扰了一段时间。

我的目标是创建一个灵活的结构数组,因为我不能使用任意限制,而且数组对我来说有 99 项的限制(*请参阅帖子末尾)。我已经使用了 realloc() 但它为无效的旧大小提供了 abort() 。但是,我尝试在另一个程序中测试动态结构数组,它工作得完美无缺。我无法弄清楚是什么导致另一个崩溃。

我的选举计划(即崩溃的计划):

注意:entr_cmd函数只是将光标移动到屏幕底部并打印文本,而STREQL只是查看两个字符串是否匹配,只是strcmp的快捷宏

struct candidate {
long lrn;
char *name;
int grade;
char *section;
char *party;
char *position;
}
**candidates,
// :: Temporary Array for storing all the candidates in the position to be voted in
**candidates_cur;
int can_c = 0;

[...]

int main() {
[...]
candidates = malloc(2 * sizeof(struct candidate *));
[...]
if(STREQL(command, "c")) {
struct candidate *c;

if(can_c > 1) {
struct candidate **tmp;
tmp = (struct candidate**) realloc(candidates, (1 + can_c) * sizeof(struct candidate *));

if(tmp != NULL) candidates = tmp;
}

candidates[can_c - 1] = malloc(sizeof(struct candidate *));
c = candidates[can_c - 1];

entr_cmd("Candidate's Name: ");
// :: This recieves the input but replaced for testing
c->name = malloc(4 * sizeof(char));
strcpy(c->name, "XXX");

can_c++;
}
[...]

完美运行的测试程序:

这会为测试结构的成员生成一个随机数字字符串

struct test {
char *name;
char *another;
int test;
} **arr;

int main() {
int r1;

arr = malloc(2 * sizeof(struct test *));

r1 = rand() % 45;
for(int i = 0; i < r1; i++) {
int r2 = rand() % 22;

if(i > 2) {
struct test **data;
data = (struct test**) realloc(arr, (2 + i) * sizeof(struct test*));

if(data != NULL) {
arr = data;
}
}

arr[i] = malloc(sizeof(struct test *));
struct test *t = arr[i];
t->name = malloc(r2 * sizeof(char));
t->another = malloc(r2 * sizeof(char));
t->test = r2;

for(int ii = 0; ii < r2; ii++) {
t->name[ii] = (char) (rand() % 9) + '0';
t->another[ii] = (char) (rand() % 9) + '0';
}

printf("====[%u]====\n%s\n%s\n%u\n", i, arr[i] -> name, arr[i] -> another, arr[i] -> test);
}

for(int i = 0; i < r1; i++) {
free(arr[i]->name);
free(arr[i]->another);
free(arr[i]);
}

free(arr);
getch();
}

任何帮助将不胜感激,因为我们的老师对我寄予厚望,并告诉我这会很容易容易,但事实证明恰恰相反。

感谢您的阅读,祝您有美好的一天!!!

额外的废话:我在一门类(class)中,我们经常使用 TurboC++ 进行编程,但是在那里做到这一点非常困难,所以我转而使用 C99 和我的 neovim 设置,这样我就可以快速导航和C99 中的大部分功能也可以在 TurboC++ 中运行。换句话说,我无法真正使用(最新标准)C++,如果是这样,我想我可能会更容易地做到这一点

最佳答案

问题与内存分配根本无关!出现问题是因为我不断分配候选者[-1],我已将候选者[can_c - 1] 放入候选者[can_c] 内存中。

感谢所有提供帮助的人! (@someprogrammerdude 指出了这一点)

关于c - realloc() 结构数组的旧大小无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58098545/

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