我正在尝试将一个结构中的字符串分配给另一个结构的字符串:
func->parameters[func->parameter_amount].name = tokens[i+1].value;
这在while循环中发生:
while (true) {
func->parameter_amount++;
func->parameters = realloc(func->parameters, func-> parameter_amount*sizeof(struct parameter));
if (func->parameters == NULL) {
mem_error();
}
if ((tokens[i].token != symbol) && (tokens[i].token != comma)) {
break;
} else if ((tokens[i].token == symbol) && tokens[i+1].token == symbol) {
func->parameters[func->parameter_amount].type = string_to_type(tokens[i].value);
if (func->parameters[func->parameter_amount].type == -1) {
printf("Error: Invalid type '%s' for parameter declaration in function '%s' on line %i\n", tokens[i].value, func->name, func->line);
exit(1);
}
func->parameters[func->parameter_amount].name = tokens[i+1].value;
i += 2;
} else if (tokens[i].token == comma) {
func->parameter_amount--;
i++;
}
}
分配完成后,程序会说:realloc(): invalid next size
并中止
结构定义为:
struct parameter {
int type;
char* name;
};
struct function {
int line;
int type;
char* name;
struct parameter* parameters;
int parameter_amount;
};
typedef struct {
int token;
char* value;
int line;
} token;
我不知道出了什么问题
您的代码中存在多个错误:
1]在realloc
之后,func->parameters
数组的大小为func->parameterAmount
。因此,这意味着最后一个索引可以使用func->parameterAmount-1
:
func->parameters[func->parameterAmount - 1]
2)对于func->parameters
数组中的每个元素,您都必须分配字符串value
(因为此时value
只是一个指向字符的指针):
int i = 0;
int n = 129; // n will be the max length (minus 1) of newly allocated string
for (i = 0; i < func->parameterAmount; ++i) {
func->parameters[i].name = (char *) malloc(sizeof(char) * n);
if (func->parameters[i].name == NULL) {
// Handle alloc error
}
}
此外,请记住在令牌value
内分配所有字符串变量array
。
3)在C中,您不能以这种方式为字符串分配值。您必须使用strcpy()
标头中的string.h
:
strcpy(func->parameters[func->parameter_amount].name, tokens[i+1].value);