c - 访问结构中的数组元素时出错

标签 c arrays pointers struct segmentation-fault

我正在尝试编写一个“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;

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

最佳答案

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

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

关于c - 访问结构中的数组元素时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35822806/

相关文章:

c - 套接字编程-简单的客户端/服务器

c - 我如何在 git 中运行命令 emerge?

PHP 在多维数组中搜索子字符串

php - 取消设置空数组元素

关于指针使用的说明

c - 运行一系列直到小数点第三位相同

c - 我无法在 c 中将一个结构分配给另一个结构

java - 方向数组: reducing complexity

c - 从C中的字符串中提取所有N位数字

C++ 类型转换指针指向常量变量