-1

こんにちは、2D 配列をらせん状に印刷するプログラムを書いていました。しかし、以下のエラーが発生していますsubscripted value is neither array nor pointer nor vector

これは私のコードです。

int *spiralOrder(const int** A, int n11, int n12, int *length_of_array) {
    *length_of_array = n11 * n12; // length of result array
    int *result = (int *)malloc(*length_of_array * sizeof(int));
    int top = 0, bottom = n11 - 1, left = 0, right = n12 - 1;
    int d = 0, j = 0, k = 0;
    while (top <= bottom - 1 && left <= right - 1) {
        int i;
        if (d == 0) { //left to right
            for (i = 0; i < right; i++) {
                result[j++][k++] = A[top][i];
            }
            top++;
            d = 1;
        } else
        if (d == 1) { //top to bottom
            for (i = 0; i < bottom; i++) {
                result[j++][k++] = A[i][right];
            }
            right--;
            d = 2;
        } else
        if (d == 2) { //bottom right to left
            for (i = right; i >= left; i--) {
                result[j++][k++] = A[bottom][i];
            }
            bottom--;
            d = 3;
        } else
        if (d == 3) {  //bottom left to top
            for (i = bottom; i >= top; i--) {
                result[j++][k++] = A[i][left];
            }
            left++;
            d = 0;
        }
    }
    return result;
}

result結果を配列に保存したい。これらのエラーに対する回答を見ましたが、それらのほとんどは 1D 配列を扱っています。誰か助けてくれませんか。

4

2 に答える 2

1

1次元配列としてmalloc編集し、それを2次元配列として使用しています。result

変数が 2 つrow_numberありcol_number、配列のサイズについては、次のように割り当てる必要がありますresult(忘れないでくださいfree())。

int **result;
result = (int**) malloc(row_number * sizeof(int*));
for(int i=0; i<row_number; i++)
{
    result[i] = (int*) malloc(col_number * sizeof(int));
}
于 2016-01-25T12:20:28.607 に答える
0

まず、結果を int* として作成していますが、int** として使用しています。
2 番目に、2D 配列を変更したくない場合は、const int** の代わりに int** const を使用します。
最後に、ロジックを正しく実装していません
。WAIT ロジックを実装できなかった場合にのみ、さらにお読みください。これが正しい実装です: http://ideone.com/DfUD2T

int *spiralOrder(int** const A, int n11, int n12, int *length_of_array) {
    *length_of_array = n11 * n12; // length of result array
    int *result = (int *)malloc(*length_of_array * sizeof(int));
    int top = 0, bottom = n11 - 1, left = 0, right = n12 - 1;
    int j = 0, k = 0;
    while (top <= bottom - 1 || left <= right - 1) {
        int i;
         //left to right
            for (i = left; i <= right; i++) {
                result[j++] = A[top][i];
            }
            top++;
            //top to bottom
            for (i = top; i <= bottom; i++) {
                result[j++] = A[i][right];
            }
            right--;
            //bottom right to left
            for (i = right; i >= left; i--) {
                result[j++] = A[bottom][i];
            }
            bottom--;
              //bottom left to top
            for (i = bottom; i >= top; i--) {
                result[j++] = A[i][left];
            }
            left++;
    }
    return result;
}
于 2016-01-25T16:23:04.710 に答える