2012-04-11 1355 views
1

我想製作一個函數,它接收一個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 []函數來釋放數組。

非常感謝您的幫助!

+0

要傳遞一個二維數組,我認爲數組參數應該是一個'int **',否則你傳遞的是一維數組。 – 2012-04-11 14:29:43

回答

4

你不能做到這一點:

int result[columns]; 

你需要一個動態分配:

int* result = new int[columns]; 

而且,你的array使用看起來是錯誤的。如果array將是一個指針,然後你想:

result[i] = array[which*columns + i]; 
2

「數組」是一維的。你可以通過array [which * columns + i]訪問index [which] [i]的元素。由於數組只是一個單獨的指針,因此還要刪除星號。

編輯:你也無法返回本地陣列 - 你需要處理動態內存:

int* result = new int[columns]; 

然後要特別小心,以釋放此內存。其他選項是使用std :: vector。

+0

s /刪除本地數組/返回本地數組/? – 2012-04-11 14:35:26

1

有跡象表明,需要先固定的幾個錯誤。

  1. 你不應該從函數返回一個指向局部變量的指針。在上面的代碼中,你試圖返回一個指向'result'的內容,這是一個局部變量。
  2. 無法聲明數組的大小是可變的,在你的情況下是變量列。
  3. 如果數組是一個二維數組,我認爲這是你的意圖,那麼array [which] [i]給你一個int。你不必去引用它。

儘管我知道我不是在這裏發帖的禮儀,但我建議您先從一本好的教科書開始,抓住基本知識,並在遇到問題時來到這裏。

1

數組的大小需要是編譯時常量。

不應該搞亂數組,你應該使用std::vector(可能還有2D矩陣類)。

0

您可以通過使用std::vector

#include <vector> 
#include <iostream> 

typedef std::vector<int> Row; 
typedef std::vector<Row> Matrix; 

std::ostream& operator<<(std::ostream& os, const Row& row) { 
    os << "{ "; 
    for(auto& item : row) { 
    os << item << ", "; 
    } 
    return os << "}"; 
} 

Row getrow(Matrix m, int n) { 
    return m[n]; 
} 

Row getcol(Matrix m, int n) { 
    Row result; 
    result.reserve(m.size()); 
    for(auto& item : m) { 
    result.push_back(item[n]); 
    } 
    return result; 
} 

int main() { 
    Matrix m = { 
    { 1, 3, 5, 7, 9 }, 
    { 2, 4, 5, 6, 10 }, 
    { 1, 4, 9, 16, 25 }, 
    }; 

    std::cout << "Row 1: " << getrow(m, 1) << "\n"; 
    std::cout << "Col 3: " << getcol(m, 3) << "\n"; 
} 
0
double *row(double **arr, int rows, int columns, int which) 
{ 
double* result = new double[columns]; 
for (int i=0; i<columns; i++) 
{ 
    result[i] = arr[which][i]; 

} 
return result; 
delete[] result; 
} 

這將返回該行避免這一切的指針運算和內存分配。