2016-11-03 29 views
-2

●int vectorInsert(Vector * array、int index、Data value);C言語の動的配列ベクトル

実行中

これは、指定されたステートメントに従って修正することができます。

私は

Vector *vect = initVector(); 
Data data_array[20]; 
for(i = 0 ; i < 20 ; i++){ 
    data_array[i].value = (rand() % 20) + 1; 
    vectorInsert(vect, i, data_array[i]); 
} 
+2

あなたが投稿したコードに問題がありますか?何を聞いていますか? –

+0

また、 'Vector'はあなたが作成した型です、これはC++の標準ライブラリ' Vector'です – Mobius

+0

Vectorを作成しました。私はもう一度コードを編集しました。 – King

答えて

0

最初に、あなたの仕様によれば、max_sizeは符号なし整数でなければならないので、これを反映するようにVectorsize_tに変更しました。この新しいタイプに合わせて、関連するフォーマット指定子を%dから%zuに変更しました。

initVector()機能がVectorのメモリを割り当てる必要があり、追加されています。さらに、ここでData構造体の動的配列にメモリを割り当てる必要がないため、v->dataNULLに設定されています。この関数は、Vector.dataフィールドへのポインタではなく、新しく割り当てられたメモリvへのポインタも返さなければなりません。

vectorInsert()関数では、メモリ割り当てエラーをチェックするのを忘れてしまったので、割り当てが試行された後にチェックが追加され、エラーがあれば0が返されます。新しいData構造体を挿入した後、インクリメント.current_sizeへのチェックが間違っています。まず、array->current_size <= indexの場合は増分する必要があります。次に、.current_sizeに1つ追加する必要があります..current_sizeをインデックス値よりも大きいものに設定しないでください。また、ここに挿入された値を印刷するときは、.valueフィールドへのアクセスを忘れました。私はこれがに渡されたData構造体のために使用した混乱した名前のためかもしれないと思います。この構造体をvalueと呼びます。前の行では、array->data[index] = valueがあり、valueという構造体をarray->data[index]に割り当てています。しかし、printf()への呼び出しでは、構造体valueが保持する値を表示する必要があります。より良い名前を選ぶことは常に勝利です!最後に、この関数は挿入が成功すると1を返します。

Iはvectvect->dataの内容を表示するテストコードに加え、また、任意のインデックスへの挿入をテストするData構造体、test_insertを添加。

最後に、この後にメモリ割り当てを解放する必要があるため、free()への2回の呼び出しを追加しました。ここで

はコードです:

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 

typedef struct 
{ 
    int value; 
}Data; 

/* Specs say that max_size should be an unsigned integer */ 
typedef struct{ 
    size_t max_size; //initialize to 0 
    size_t current_size; //initialize to 0 
    Data *data; // array of integers we're storing 
} Vector; 

/* Modified function */ 
Vector * initVector(void){ 
    Vector *v = malloc(sizeof(*v)); 
    v->max_size=0; 
    v->current_size=0; 
    v->data = NULL; 
    return v; 
} 

int vectorInsert(Vector * array, size_t index, Data value) 
{ 
    if(index >= array->max_size) 
    { 
     array->max_size = index * 2 + 1; 
     printf("Inside Vect max_size is : %zu\n", array->max_size); 

     Data *new_array = malloc(sizeof(Data) * array->max_size); 

     /* Added check for allocation error */ 
     if (new_array == NULL) 
      return 0; 

     if(array->data != NULL) 
     { 
      memcpy(new_array, array->data, sizeof(Data)*array->current_size); 
      free(array->data); 
      array->data = NULL; 
     } 
     array->data = new_array; 
    } 

    array->data[index] = value; 

    printf("Main : %d\n", array->data[index].value); 

    /* Modified current_size increment logic */ 
    if(array->current_size <= index) 
    { 
     array->current_size += 1; 
    } 

    /* Successful insertion */ 
    return 1; 
} 

int main(void) 
{ 
    size_t i; 
    Vector *vect = initVector(); 
    Data data_array[20]; 
    Data test_insert = { -5 };  // to test index insertion 

    for(i = 0 ; i < 20 ; i++){ 
     data_array[i].value = (rand() % 20) + 1; 
     vectorInsert(vect, i, data_array[i]); 
    } 

    /* Display results */ 
    printf("vect->max_size = %zu\n", vect->max_size); 
    printf("vect->current_size = %zu\n", vect->current_size); 
    printf("vect->data contains:\n"); 
    for (i = 0; i < vect->current_size; i++) 
     printf("%d ", vect->data[i].value); 
    putchar('\n'); 

    /* Insert test_insert at index 5 */ 
    vectorInsert(vect, 5, test_insert); 

    /* Display results */ 
    printf("vect->max_size = %zu\n", vect->max_size); 
    printf("vect->current_size = %zu\n", vect->current_size); 
    printf("vect->data contains:\n"); 
    for (i = 0; i < vect->current_size; i++) 
     printf("%d ", vect->data[i].value); 
    putchar('\n'); 

    /* Free memory allocations */ 
    free(vect->data); 
    free(vect); 

    return 0; 
} 

そして、ここでは、結果のサンプルです:

vect->max_size = 31 
vect->current_size = 20 
vect->data contains: 
4 7 18 16 14 16 7 13 10 2 3 8 11 20 4 7 1 7 13 17 

vect->max_size = 31 
vect->current_size = 20 
vect->data contains: 
4 7 18 16 14 -5 7 13 10 2 3 8 11 20 4 7 1 7 13 17 
0

(例えばgcc -Wall -gでコンパイル)コンパイラのすべての警告およびデバッグ情報を有効に利用し、それを呼び出しています。そして、それはあなたに警告しなければならない程度

Vector * initVector(){ 
Vector *v; /// UNINITALIZED 
v->max_size=0; 
v->current_size=0; 
v->data = malloc(sizeof(int)*v->max_size); 
return v->data; 
//  return (&v); 
} 

だから、 undefined behaviorを持って、それは awfully badです。あなたが読みたいと思うかもしれません

(もちろん、あなたがgdbデバッガを使用する必要があります。コンパイラは、他の警告の多くを与えるだろう、とあなたはまったくの警告を得なかったまであなたのコードを向上させる必要があります)

flexible array members

は、おそらく、少なくとも持つ考えてみましょう:

Vector* createVector(int maxsize) { 
    if (maxsize<=0) 
    { fprintf(stderr, "bad maxsize=%d\n", maxsize); exit(EXIT_FAILURE); }; 
    Vector* v = malloc(sizeof(Vector)); 
    if (!v) { perror("malloc Vector"); exit(EXIT_FAILURE); }; 
    v->data = malloc(sizeof(Data)*maxsize); 
    if (!v->data) { perror("malloc data"); exit(EXIT_FAILURE); }; 
    v->max_size = maxsize; 
    v->current_size = 0; 
    memset(v->data, 0, sizeof(Data)*maxsize); 
    return v; 
} 
+0

program5.c:関数 'initVector'で: program5.c:23:3:警告:互換性のないポインタ型からの戻り値[デフォルトで有効] program5.c: vectorInsert ': program5。c:37:4:警告:組み込み関数 'memcpy'の暗黙の宣言[デフォルトで有効] program5.c:51:4:警告:キャストなしでポインタから整数を返す[デフォルトで有効] program5 .c:51:4:warning:関数はローカル変数のアドレスを返します[デフォルトで有効] 私は警告を訂正できません。 – King

+0

その後、すべての警告を修正する前にフォーラムで質問しないでください。しかし、あなたのCチュートリアルや良いCプログラミングの本をもっと深く読むには数時間かかるでしょう。 –

+0

パラメータとしてint maxsizeを使用することはできません。パラメータはありません。 – King

1

あり、あなたのコード内のエラーのカップルがありますが、最も重要なものは、あなたのinitVector機能であり、あなたが実際にベクトル用のメモリを割り当てる必要があります。エラーを追加し、initVectorリターンvの代わりに、v->dataまたは成功にvectorInsertリターン1array->data[index].value代わりarray->data[index]

  • &v
  • vectorInsertの印刷に

    • はまた、次のことを行う必要がありあなたの割り当てをチェックし、メモリエラーで0を返してください。

    元のmallocを除いて、これらはすべて、コンパイラから返された警告です。

  • +0

    第3部についてどうやって行くのですか? – King

    +0

    私の答えを見てください。私は* crudely * allocationの失敗を処理しました。 –

    +1

    あなたが知らない場合は、関数内に複数の 'return'ステートメントを置くことができます。最初に取得すると関数が終了するので、エラーが発生した場合は、ifステートメントを使用してチェックしますエラーを返し、if文の中で 'return 0'を実行します。 – Mobius

    関連する問題