2016-04-11 11 views
-8

malloc()関数を使用して、以下で定義されたADTを使用して整数配列を作成しようとしています。私はそれがintarr_t型の新たに割り当てられた整数配列へのポインタを返すようにしたい。それが動作しない場合 - 私はnullポインタを返すようにします。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; 
} 

テストはaboutsは、私がここに間違っている

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

私は、このエラーを与えていますか?

+2

構造内の* member * 'data'に動的にメモリを割り当てることが目的だと思います。 –

+4

あなたは 'intarr_t'要素のためのスペースを割り当てています...しかし、各要素の' int * data'フィールドのためにスペースを割り当てるのはどうですか?そして、各要素のすべてのフィールドを初期化するのはどうですか? – paulsm4

+0

どうすればそれをやりますか?私はまだこのようなmallocとtypedefを使用することに慣れていません。 =/ –

答えて

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

私はどこにも使われていないので、forループは何も繰り返されません。 –

+0

@Code_Penguinそれは悪いです。私は「私」を宣言するのを忘れた。編集された草。 –

+0

したがって、forループは、サイズがlen、len倍の各データメンバのサイズintのメモリを作成していますか? –

関連する問題