【问题标题】:Creating array of pointers to struct inside a struct在结构内创建指向结构的指针数组
【发布时间】:2016-06-04 10:32:48
【问题描述】:

基本上,我有一个这样定义的结构:

struct D_Array
{
    int Capacity;
    int Cur_Size;
    struct Student* List;
};

现在,在创建结构之后;

struct D_Array* T_Array;
if (T_Array = malloc(sizeof(struct D_Array)) == NULL)
{
    printf("There has been a problem with memory allocation. Exiting the program.");
    exit (21);
}

我在此结构中创建学生列表时遇到问题。我需要列表是一个指针数组,因为我应该制作某种 ADT 程序,所以我试图让它像这样:

T_Array->Capacity = 10;
T_Array->Cur_Size = 0;
T_Array->List[10]= (struct Student*) malloc(sizeof (struct Student*));

无论我如何尝试更改它,我都会遇到同样的错误: 从“struct Student *”类型分配给“struct Student”类型时不兼容的类型|

我正在尝试创建一个可以执行类似操作的数组;

T_Array->List[1]=Student_Pointer;

谢谢!

【问题讨论】:

    标签: c arrays pointers struct abstract-data-type


    【解决方案1】:

    将数组的类型更改为 struct Student** 这将是指针数组:

    struct student * --> 指向学生的指针。 struct student ** --> 指向 student 的指针(你需要的)。

    struct D_Array
    {
        int Capacity;
        int Cur_Size;
        struct Student** List;
    }
    

    和分配:

    T_Array->List = malloc (sizeof (struct Student*) *  lengthofarray);
    

    然后:

    T_Array->List[1]=Student_Pointer;
    

    【讨论】:

    • 不要转换malloc的结果。在sizeof (struct student*)x lengthofarray x 应该是*。
    • Don't cast the result of malloc。如果你认为你需要它,你要么使用了错误语言的编译器,要么忘记了#include 所需的标头。
    • @Dr.Haimovitz void 会自动转换为分配给它的变量的数据类型......那为什么要在自动完成时再次进行强制转换?
    • "malloc 返回 void* 这显然不是学生*,所以你需要一个演员" 不需要,在 C 中也不推荐以任何方式,C 隐含地从和到空指针。这在 C++ 中是不同的。
    • 如果你没有在 64 位系统上包含 malloc() 的原型,它的返回类型将默认为 int,是的。编译器会检测到这个和错误。如果您通过强制转换应用显式转换到void*,编译器只会发出警告(或什么都不记录),它肯定不会出错。仍然malloc() 将仅返回 32 位(int 的宽度),并且错过了 void* 的上 32 位,它应该返回有或没有强制转换。结论:演员隐藏了错误,程序将失败。不是很好。不要在不需要的地方进行转换(例如调用accept()。
    【解决方案2】:

    struct Student* List; List 是 Student 的指针 当您执行 List[10] 时,您所做的基本上是 *(List+10) 表示从第 11 位获得学生

    如果你想要一个指针数组,你需要做类似的事情

    struct Student **List;
    然后
    List = (Student **)malloc(10*sizeof(Student **))
    然后,List 将为 10 个学生指针分配内存,最终每个指针的大小为 int

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-01-29
      • 1970-01-01
      • 2017-06-03
      • 1970-01-01
      • 1970-01-01
      • 2012-07-16
      相关资源
      最近更新 更多