gpt4 book ai didi

c - 如何正确地将值复制到数组元素中?

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

我需要一个将值放入数组的通用函数,我是这样写的:

int add_element(void** arr, void* val, int t_size, int* size, int* capacity) {

if ((*size) == (*capacity)) {
*capacity += ARRAY_INC;
*arr = (char*)realloc(*arr, (*capacity) * sizeof(char));

if (*arr == NULL) {
return 1;
}
}

memcpy(*arr + ((*size)++), val, t_size);

return 0;
}

它非常适合 char 数组,但我在接下来的代码中遇到结构数组的问题:

int scan_tokens(Token** p_tokens, int* size) {
char* line;
int len;

if (get_line(&line, &len)) {
return 1;
}

int capacity = ARRAY_INC;
*size = 0;
*p_tokens = (Token*)malloc(capacity * sizeof(Token));
int start = -1;

for (int i = 0; i < len; ++i) {
char ch = line[i];

if (isdigit(ch)) {

if(start == -1) {
start = i;
}
} else {
if (start != -1) {
Token t;
int count = i - start;
t.size = count;
t.data.token = (char*)malloc(count * sizeof(char));
memcpy(t.data.token, line + start, count * sizeof(char));
start = -1;
add_element(p_tokens, &t, sizeof(Token), size, &capacity);
}

Token t;

switch(ch) {
case SUM:
case SUB:
case MUL:
case DIV:
case LBR:
case RBR:
t.size = 0;
t.data.ch = ch;
add_element(p_tokens, &t, sizeof(Token), size, &capacity);
break;
default:
return 1;
}
}
}

if (start != -1) {
Token t;
int count = len - start;
t.size = count;
t.data.token = (char*)malloc(count * sizeof(char));
memcpy(t.data.token, line + start, count * sizeof(char));
start = -1;
// Will a copy of `t` in p_tokens be reseted on the next iteration?
add_element(p_tokens, &t, sizeof(Token), size, &capacity);
}

free(line);
line = NULL;

return 0;
}

问题是添加的数组元素在下一次循环迭代时被重置。我不明白为什么?当我在 add_element 中调用 memcpy 时,它必须将 Token 结构的所有字段复制到数组元素结构的相关字段中,不是吗?
我做错了什么以及如何解决?我已经无法获得...

已修复的次要错误

int add_element(void** arr, void* val, int t_size, int* size, int* capacity) {

if ((*size) == (*capacity)) {
*capacity += ARRAY_INC;
*arr = realloc(*arr, (*capacity) * t_size);

if (*arr == NULL) {
return 1;
}
}

memcpy(*arr + ((*size)++), val, t_size);

return 0;
}

代码还是有同样的问题。
已添加
似乎我得到了我的错误,它在这里 *arr + ((*size)++): arr is void** 所以也许 (*arr + some_num) 会给出错误的偏移量,但我不知道如何修复它。

最佳答案

scan_tokens 中,您有初始分配:

*p_tokens = malloc(capacity * sizeof(Token));

[删除不必要的转换]

在这里你分配了 capacity * sizeof(Token) 字节。

然后在 add_element 中你有:

*arr = realloc(*arr, (*capacity) * sizeof(char));

在这里你分配了*capacity字节。

这当然是不正确的,很可能会分配给 little。在 add_element 函数中,您应该分配多个 t_size 字节:

*arr = realloc(*arr, (*capacity) * t_size);

一个非常相关的注意事项:不要重新分配回您传递给 realloc 的指针功能。如果 realloc 失败,它将返回一个空指针,导致您丢失原始指针。使用您在分配之前检查的临时变量。

关于c - 如何正确地将值复制到数组元素中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46517123/

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