c - 在结构的动态数组上使用 realloc 时出现段错误

标签 c segmentation-fault realloc

我有一大段代码有问题,所以我尽可能地减少它,事实上我找到了解决我的问题的方法,但我几乎可以肯定有更好的解决方案,这就是为什么我在寻求帮助。

这是错误的代码:

#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/

相关文章:

函数中的 C++ 段错误

c - 如何为二维 float 组重新分配内存?

将段落转换为具有动态内存的句子

c - 重新分配一个字符串数组

c - 如何从 C 文件中读取复数?

C:对 'clock()' 的 undefined reference

c++ - 设置 bool 时可能出现段错误?

c - 如何检查列表中的下一个元素是否超出范围?

objective-c - 字节数组加倍

c++ - flex 没有生成 yyFlexLexer.h header