您好我正在编写以螺旋顺序打印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数组。有人可以帮忙。
答案 0 :(得分:0)
您malloc
编辑result
作为1维数组,并将其用作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));
}
答案 1 :(得分:0)
首先,您将结果创建为int *,但将其用作int ** 其次,如果您不打算更改2D数组,请使用int ** const而不是const int ** 最后,您没有正确实现逻辑,左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;
}