在struct中访问数组元素时出错

我正在尝试编写一个“ArrayList”程序(类似于Java ArrayList ),它将使用realloc自动扩展,这样程序员就不必担心数组中的存储空间。 这是我的代码:

 #include  #include  #include  #include  #define ARR_DEFAULT_SIZE 20 #define INCR 10 #define ARRTYPE char // Files using this #undef this macro and provide their own type typedef struct { ARRTYPE *arr; long size; long nextincr; } arrlst; arrlst *nlst(void); void add(arrlst *, ARRTYPE); ARRTYPE elmat(arrlst *, long); int main(int argc, char **argv) { arrlst *lst = nlst(); add(lst, 'h'); } arrlst *nlst() { arrlst lst = { malloc(ARR_DEFAULT_SIZE), 0, ARR_DEFAULT_SIZE }; arrlst *lstptr = &lst; return lstptr; } void add(arrlst *lst, ARRTYPE elm) { if (lst->size >= lst->nextincr) { ARRTYPE *tmp = lst->arr; lst->nextincr += INCR; lst->arr = realloc(lst->arr, lst->nextincr); for (int i = 0; i arr[i] = tmp[i]; } lst->arr[lst->size++] = elm; } ARRTYPE elmat(arrlst *lst, long at) { if (lst->size arr[at]; } 

我的问题是每当我运行它时,调用add()会产生段错误,并且因为第一次调用它时跳过add()大多数代码,所以错误行必须是:

 lst->arr[lst->size++] = elm; 

我不知道为什么会出现这种错误。 请帮忙!

因为在nlst你返回一个指向局部变量的指针,并且局部变量超出范围并且当它们被定义的函数返回时“死”。 使用该指针将导致未定义的行为 ,这是崩溃的一个非常常见的原因。

您有两个解决方案: nlst应该动态分配arrlst结构并返回该指针。 或者传入指向arrlst结构的指针,从而模拟按引用传递。