【问题标题】:Realloc array of pointers to an Struct in C [closed]指向 C 中 Struct 的指针的 Realloc 数组 [关闭]
【发布时间】:2016-06-07 11:05:04
【问题描述】:

我有一个这样的结构:

struct _Total {
    Socio *socio[0];
    Libro *libro[0];
    int numsocios;
    int numlibros;
};

我在大学实习,每次添加数据时都需要重新分配“socio”和“libro”指针。例如,如果 a 只有一个“socio”,则数组的大小必须为 1,如果我添加另一个“socio”,我需要将其重新分配为大小 2,然后将指针添加到新结构(计数器是“numsocios ”)。 “libro”也一样。

我尝试了这个函数(total.c 文件),但显然我遇到了类型错误:

STATUS total_ajustarsocio(Socio **socio, int tam) {

    Socio *temp = NULL;

    if (!socio) {
        return ERROR;
    }

    temp = (Socio *) realloc (*socio, tam * sizeof(Socio));

    if (!temp) {
        printf("Error reallocating Socio");
        return ERROR;
    }

    *socio = temp;

    return OK;
}

那么,我该如何解决mi问题呢?

附:这是 Socio 结构(在 social.c 中 - 它在这个文件中也有 malloc 和 free 的功能)。

struct _Socio {
    char nombre[MAXCAR];
    char apellido[MAXCAR];
    int dni;
    char direccion[MAXCAR];
    int tlf;
    int numprestamos;
};

谢谢!

【问题讨论】:

  • 我没有发现任何问题。为什么你认为你有一个?
  • 提供minimal reproducible example。也不要将malloc 和朋友的结果投射到 C 中。
  • Socio *libro [0]" 在我看来非常、非常、非常可疑。
  • 下划线开头的全局标识符对于隐藏实现细节非常方便。不幸的是,标准委员会也这么认为并保留了它们。不要为您的类型或函数使用以下划线开头的名称,否则您可能会发现自己遇到奇怪的构建问题。
  • @Maria 请尝试将Socio 替换为struct _Socio 内的realloc (*socio, tam * sizeof(Socio))

标签: c arrays pointers struct realloc


【解决方案1】:

您的struct _Total 错误。应该是:

struct _Total {
    Socio *socio;
    Libro *libro;
    int numsocios;
    int numlibros;
};

您的 total_ajustarsocio 函数可能会被这样调用:

total.numsocios++;
err = total_ajustarsocio(&total.socio, total.numsocios);

【讨论】:

  • 我在 2 票赞成后编辑了我的答案,因为我认为我的原始答案与 OP 试图完成的不匹配。
  • 谢谢,我昨天测试了它,但我无法通过这个实现访问数组。 total.c:40:36: 错误:取消引用指向不完整类型的指针 destruir_socio(total->socio[i]);
  • 进入struct _TotalSocio *socio; 应该是struct Socio *socio;libro 相同。
  • @MartaGarcia 问题在于struct _Socio 的可见性。将它移到Socio.h,它应该自然放置在typedef之前。
  • @LPs 谢谢!是的,这就是解决方案。是因为隐藏植入,但我不需要隐藏这个,所以现在解决了。
猜你喜欢
  • 1970-01-01
  • 2018-03-25
  • 1970-01-01
  • 2015-02-04
  • 1970-01-01
  • 2012-08-20
  • 2018-08-26
  • 2013-04-30
  • 2013-10-14
相关资源
最近更新 更多