2016-04-11 52 views
-8

我想創建一個整數數組,使用malloc()函數下面定義的ADT。我希望它返回一個指向新分配的intarr_t類型的整型數組的指針。如果它不起作用 - 我希望它返回一個空指針。使用Malloc()創建一個整數數組使用指針

這是我迄今爲止 -

//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) 

哪裏abouts我已經錯了這裏?

+2

我認爲目的是動態地爲結構中的* member *'data'分配內存。 –

+4

您正在爲一堆'intarr_t'元素分配空間......但是如何爲每個元素中的「int * data」字段分配空間?那麼初始化每個元素的所有字段呢? – paulsm4

+0

我該怎麼做呢?我不是很熟悉使用malloc和typedefs。 =/ –

回答

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 
} 
+0

Theres沒有在循環中得到迭代,因爲我沒有在任何地方使用,是由設計? –

+0

@Code_Penguin Ops這是我的壞。我忘了宣佈'我'。編輯的割草。 –

+0

因此,您的for循環只是在大小爲len,len次的ia中爲每個數據成員創建int大小的內存? –