我想製作一個函數,它接收一個2維數組並將其行('which')之一作爲簡單數組返回。我寫到:從二維數組中提取行或列C++
int *row(int *array, int lines, int columns, int which)
{
int result[columns];
for (int i=0; i<columns; i++)
{
result[i] = *array[which][i];
}
return result;
}
但是,在第7行中,我得到了以下錯誤:數組下標的無效類型'int [int]'。任何想法如何正確地做到這一點?我也嘗試將2D數組作爲數組的數組處理,但沒有成功。我是新手,所以請避免太先進的概念。
感謝您的幫助!
更新:感謝您的幫助!現在我的代碼如下所示:
int n; //rows
int m; //columns
int data[100][100];
int array[100];
int *row(int *array, int rows, int columns, int which)
{
int* result = new int[columns];
for (int i=0; i<columns; i++)
{
result[i] = *array[which*columns+i];
}
return result;
delete[] result;
}
int main()
{
array=row(data, n, m, 0);
}
我仍然可以在主要的錯誤:不兼容的類型中的「詮釋*」分配「INT [100]」
可能是什麼問題呢?我也不知道在哪裏使用delete []函數來釋放數組。
非常感謝您的幫助!
要傳遞一個二維數組,我認爲數組參數應該是一個'int **',否則你傳遞的是一維數組。 – 2012-04-11 14:29:43