我有一大段代码有问题,所以我尽可能地减少它,事实上我找到了解决我的问题的方法,但我几乎可以肯定有更好的解决方案,这就是为什么我在寻求帮助。
这是错误的代码:
#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;
}
输出是:
Adding struct number 0
Struct added
Adding struct number 1
zsh: segmentation fault ./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;
}
它的输出是正确的:
Adding struct number 0
Struct added
Adding struct number 1
Struct added
Adding struct number 2
Struct added
感谢阅读:)
最佳答案
你应该使用
(*tab)[i].a = i*8;
访问字段a
关于c - 在结构的动态数组上使用 realloc 时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12785820/