0

DPを使用して、配列内のインデックスiからインデックスjまでの最大項目と最小項目を含むテーブルを埋めています。このアプローチが効率的であるかどうかは、私にとって問題ではありません。
以下のコードスニペットについて考えてみます。

typedef struct Slot
{
    int min;
    int max;
}Slot;

typedef struct Table
{
    Slot* *array;
    int size;
}Table;

Table* createTable( int size )
{
    Table* table = malloc( sizeof( Table ) );

    if( !table )
            return NULL;

    table->array = ( Slot(*)[size] ) malloc( size * size * sizeof( Slot ) );

    if( !(table->array) )
                    return NULL;

    table->size = size;

    return table;
}

void foo( int arr[], int size )
{
    Table* table = createTable( size );

    if( table == NULL )
    {
            printf( "Out of memory" );
            return;
    }

    int i;

    for( i = 0; i < size; ++i )
            (table->array[i][i]).min = (table->array[i][i]).max = arr[i]; <----------
}

ランタイムエラーが発生します。以下の2つのステートメントにコメントすると、正常に実行されます

for( i = 0; i < size; ++i )
            (table->array[i][i]).min = (table->array[i][i]).max = arr[i]; <----------

なぜランタイムエラーが表示されるのですか?

4

1 に答える 1

1

malloc2D配列のがSlot間違っています:

table->array = ( Slot(*)[size] ) malloc( size * size * sizeof( Slot ) );

これの代わりにこれを行う必要があります:

 table->array = (Slot**) malloc(sizeof(Slot*));
   for (int i = 0; i < ArraySizeX; i++)
        table->array[i] = (Slot*) malloc(ArraySizeY*sizeof(Slot));

mallocまたは、1回の呼び出しでそれを実行したい場合は、次のようSlot*にしますTable

table->array = (Slot*) malloc(SizeX * SizeY * Sizeof(Slot));

これにより、double配列が適切に割り当てられます。

次に、この構成:

  for( i = 0; i < size; ++i )
     (table->array[i][i]).min = (table->array[i][i]).max = arr[i];

実際には、一度に1つの割り当てを行う必要があります。

  for( i = 0; i < sizeX; ++i )
  {
      (table->array[i][i]).max = arr[i];
      (table->array[i][i]).min = (table->array[i][i]).max;
  }
于 2012-09-14T10:09:29.857 に答える