gpt4 book ai didi

c - free() 不接受结构类型

转载 作者:太空宇宙 更新时间:2023-11-04 05:52:44 24 4
gpt4 key购买 nike

#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>

typedef struct STATE STATE;
typedef struct TRANSITION TRANSITION;

struct STATE {
char name[4];
bool initial_state;
bool final_state;
TRANSITION *transitions;
int numberTransitions;
};

struct TRANSITION {
char c;
STATE *destination;
};

STATE *create_state(char *name, bool is_initial, bool is_final);
void add_transition(STATE *source, char sign, STATE *dest);
void destroy_state(STATE **pp_state);

STATE *create_state(char *name, bool is_initial, bool is_final) {
STATE *state = malloc(sizeof(STATE));
strcpy(state->name, name);
state->initial_state = is_initial;
state->final_state = is_final;
state->transitions = NULL;
state->numberTransitions = 0;
return state;
}

void add_transition(STATE *source, char sign, STATE *dest) {
if (source->transitions == NULL) {
TRANSITION *transitions = malloc(sizeof(TRANSITION));
transitions->c = sign;
transitions->destination = malloc(sizeof(STATE));
transitions->destination = dest;
source->transitions = transitions;
source->numberTransitions = 1;
} else {
TRANSITION *transitions = source->transitions;
int numberTransitions = source->numberTransitions;
size_t new_size = sizeof(transitions) + sizeof(TRANSITION);
transitions = realloc(transitions, new_size);
transitions[numberTransitions].c = sign;
transitions[numberTransitions].destination = dest;
(source->numberTransitions)++;
}
}

void destroy_state(STATE **pp_state) {
TRANSITION *transitions = (*pp_state)->transitions;
int numberTransitions = (*pp_state)->numberTransitions;
int i = 0;
for (i = 0; i < numberTransitions; i++) {
free(transitions[i]);
transitions[i] = NULL;
}
}

我的异常(exception)是 transitions[i] 的类型与 methods 参数不兼容。该方法调用有什么问题? Transitions 是一种结构。

编辑:我添加了其他方法,因为它是被请求的。

EDIT2: 好的,我发现如果我的 STATE 只有一个 TRANSITION,我可以释放 TRANSITION 指针。所以我的猜测是,当我尝试为额外的转换重新分配内存时,我在重新分配时犯了一个错误。

size_t new_size = sizeof(transitions) + sizeof(TRANSITION);
transitions = realloc(transitions, new_size);

最佳答案

free(transitions[i]);

transitions[i] 不是要传递给 free 的任何指针类型。 transitions 是指向结构的指针,但 transition[i] 变成了结构变量(不是指针类型),因此不应传递给 免费 .

这样做-

free(transitions);

关于c - free() 不接受结构类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35685826/

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