【问题标题】:Error while accessing element of array in struct访问结构中的数组元素时出错
【发布时间】:2016-06-19 18:25:18
【问题描述】:

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

#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];
}

我的问题是,每当我运行它时,调用add() 都会产生段错误,并且由于add() 中的大部分代码在第一次调用时被跳过,所以错误行必须是:

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

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

【问题讨论】:

    标签: c arrays pointers struct segmentation-fault


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢!我使用了动态分配,效果很好。
    猜你喜欢
    • 2021-09-20
    • 1970-01-01
    • 1970-01-01
    • 2013-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-21
    • 1970-01-01
    相关资源
    最近更新 更多