C语言 2D 数组出错:下标值既不是数组也不是指针也不是矢量



嗨,我正在编写以螺旋顺序打印 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。我看到了这些错误的答案,但其中大多数都在处理一维数组。有人可以帮忙吗?

malloc ed result 作为一个一维数组,你把它作为一个 bidemsnionnal 数组。

假设您有两个变量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));
}

首先,您将结果创建为 int*,但将其用作 int**。
其次,如果您打算不更改 2D 数组,请使用 int** const 而不是 const int**。
最后,您没有正确实现逻辑,等待
只有在无法实现逻辑时才进一步阅读。这是正确的实现: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;
}

相关内容

  • 没有找到相关文章

最新更新