错误而在结构访问数组元素 [英] Error while accessing element of array in struct
问题描述
我试图写一个的ArrayList计划(到Java的 的ArrayList
),将使用的 的realloc
,这样程序员就不必担心数组的存储空间。这是我的code:
I'm trying to write an "ArrayList" program (Similar to the Java ArrayList
) that will expand automaticly using realloc
, so that the programmer won't have to worry about storage space in arrays. This is my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#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 < sizeof tmp; i++)
lst->arr[i] = tmp[i];
}
lst->arr[lst->size++] = elm;
}
ARRTYPE elmat(arrlst *lst, long at) {
if (lst->size < at)
strerror(14);
return lst->arr[at];
}
我的问题是,每当我运行此,调用添加()
产生一个段错误,并且由于在大部分code的补充()
就第一时间跳过调用它,错误的行必须是:
My problem is that whenever I run this, calling add()
produces a segfault, and since most of the code in add()
is skipped on the first time calling it, the line of error must be:
lst->arr[lst->size++] = elm;
我不知道为什么会出现段错误。请帮助!
And I don't know why this would segfault. Please help!
推荐答案
由于在 NLST
返回一个指针指向一个局部变量和局部变量超出范围和死的时候,它们的功能在返回的定义。使用该指针将导致的未定义行为的,这是崩溃一个非常常见的原因。
Because in nlst
you return a pointer to a local variable, and local variables goes out of scope and "dies" when the function they are defined in returns. Using that pointer will lead to undefined behavior, which is a very common reason for crashes.
您有两种解决方法:要么 NLST
应该动态分配 arrlst
结构并返回指针。或者你在一个指针传递 arrlst
结构,从而通过模拟参考合格。
You have two solutions: Either nlst
should dynamically allocate the arrlst
structure and return that pointer. Or you pass in a pointer to an arrlst
structure, thereby emulating pass by reference.
这篇关于错误而在结构访问数组元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!