【问题标题】:Using Malloc() to create an integer array using pointer [closed]使用 Malloc() 使用指针创建整数数组 [关闭]
【发布时间】:2016-04-11 06:29:44
【问题描述】:

我正在尝试使用 malloc() 函数使用下面定义的 ADT 创建一个整数数组。我希望它返回一个指向新分配的 intarr_t 类型的整数数组的指针。如果它不起作用 - 我希望它返回一个空指针。

这是我目前所拥有的 -

//The ADT structure

typedef struct {
  int* data;
  unsigned int len;
} intarr_t;

//the function 

intarr_t* intarr_create( unsigned int len ){

    intarr_t* ia = malloc(sizeof(intarr_t)*len);
    if (ia == 0 )
        {
            printf( "Warning: failed to allocate memory for an image structure\n" ); 
            return 0;
        }
    return ia;
}

我们系统的测试给了我这个错误

intarr_create(): null pointer in the structure's data field
stderr 
(empty)

我到底哪里出错了?

【问题讨论】:

  • 我认为目的是为结构中的memberdata动态分配内存。
  • 您正在为一堆intarr_t 元素分配空间......但是为每个元素中的int * data 字段分配空间呢????那么初始化每个元素的所有字段呢???
  • 我该怎么做呢?我对使用这样的 malloc 和 typedef 还不是很熟悉。 =/
  • 分配 one intarr_t 结构,然后为 data 成员初始化 len 整数。我把它作为一个练习留给你,你应该将len 结构成员初始化为。

标签: c pointers abstract-data-type


【解决方案1】:

从错误消息intarr_create(): null pointer in the structure's data field可以推断,每个结构的data字段都应该被分配。

intarr_t* intarr_create(size_t len){
    intarr_t* ia = malloc(sizeof(intarr_t) * len);
    size_t i;
    for(i = 0; i < len; i++)
    {
        // ia[len].len = 0; // You can initialise the len field if you want
        ia[len].data = malloc(sizeof(int) * 80); // 80 just for example
        if (ia[len].data == 0)
        {
            fputs("Warning: failed to allocate memory for an image structure", stderr); 
            return 0;
        }
    }
    return ia; // Check whether the return value is 0 in the caller function
}

【讨论】:

  • for 循环中没有任何东西可以迭代,因为 i 没有在任何地方使用,这是设计使然吗?
  • @Code_Penguin Ops 这是我的错。我忘了声明i。编辑割草。
  • 所以你的 for 循环只是为 ia 中大小为 len、len 次的每个数据成员创建大小为 int 的内存?
  • @Code_Penguin 是的。
  • *80有什么作用?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-10-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多