我有一段代码存在问题,所以我尽可能地减少了它,事实上我找到了解决方案来解决我的问题,米几乎肯定有更好的解决方案,这就是为什么我要求帮助。在动态数组结构上使用realloc时发生Segfault错误
这里是不好的代码:
#include <stdio.h>
#include <stdlib.h>
typedef struct{
int a;
}my_struct;
void tab_add(my_struct** tab, int i){
*tab = (my_struct*)realloc(*tab, i+1); // Here's the realloc
printf("Adding struct number %d\n", i);
tab[i]->a = i*8; // Problem here, when accessing tab[i] the second time
printf("Struct added\n");
}
int main(void){
my_struct* tab = NULL;
tab_add(&tab, 0);
tab_add(&tab, 1);
tab_add(&tab, 2);
return 0;
}
的输出是:
添加结构编号0
STRUCT加入
添加结构数1
zsh的:分段故障./main
现在,这里是解决该问题的代码(但它创建了一个无用的变量...):
#include <stdio.h>
#include <stdlib.h>
typedef struct{
int a;
}my_struct;
void tab_add(my_struct** tab, int i){
*tab = (my_struct*)realloc(*tab, i+1);
printf("Adding struct number %d\n", i);
my_struct st; // Useless variable created
st.a = i*8;
(*tab)[i] = st;
printf("Struct added\n");
}
int main(void){
my_struct* tab = NULL;
tab_add(&tab, 0);
tab_add(&tab, 1);
tab_add(&tab, 2);
return 0;
}
它的输出是正确的:
添加结构数0
结构添加
加入结构数1
STRUCT加入
添加结构数2
STRUCT加入
感谢您的阅读:)
它的工作原理!谢谢。我真的认为编译器正在用(* tab)[x] .x代替tab [x] - > b!它究竟发生了什么变化? – user1729422
'tab [x] - > b'是'(* tab [x])。b'不是'(* tab)[x] .b' –
好的,谢谢:) – user1729422