2012-03-12 3 views
0

파일에서 2 차원 배열, 행렬로 고도 값을 읽는 프로그램에서이 배열을 찾은 다른 함수에 전달하려고합니다. 최대치 기본적으로 배열은 참조로 전달된다는 것을 이해합니다. 그러나 함수의 배열 값을 변경하려고하지는 않으므로이 점이 중요하지 않습니다. 배열 호출에 대한 여러 페이지를 읽었지만 코드를 컴파일 할 때 발생하는 오류 유형에 대한 언급을 찾을 수 없었습니다. 문제는 호출되는 인수 또는 호출되는 방식에있는 것 같지만 함수의 다양한 모양에서 불일치를 볼 수 없습니다. 내 추측으로는 클래스에서 말하지 않은 2 차원 배열을 전달하는 것에 대해 뭔가있는 것 같아요. 아직 배웠던 것은 아닙니다. 어떤 도움이라도 대단히 감사하겠습니다. 코드는 다음과 같습니다2 차원 배열을 double 함수로 전달할 때 오류가 발생했습니다.

오류 : 두 배 (*) (((긴 부호없는 int)를 (((긴 '변환 할 수 없습니다

#include <fstream> 
#include <iostream> 
#include <string> 
#include <cstdlib> 

using namespace std; 

// First instance of function declaration 
double find_max(double elevations[][3600], double ilat, double ilon, int nlat, int nlon); 

int main(int argc, char *argv[]) { 

// Declare program variables 
double lat_init, lon_init; 
double lat_res, lon_res; 
double peak, valley; 
int lon_col, lat_row; 
string indat, inpoints; 
. 
. 
. 
double elevations[lat_row][lon_col]; 

// Open and read topographic data file 
ifstream topo_points; 
topo_points.open(inpoints.c_str()); 

for (int i=0; i<lat_row; i++) { 
    for (int j=0; j<lon_col; j++) 
     topo_points >> elevations[i][j]; 
} 

// Call function to find peak in the data 
peak = find_max(elevations, lat_init, lon_init, lat_row, lon_col); 

return 0; 

} 


// ***** Here lie the functions ***** 

// This function reads in the array of elevations, initial latitude and longitude 
// of the data, and the number of data points and uses this information to find 
// the latidude and longitude of the highest point on earth 
double find_max(double elev[][3600], double ilat, double ilon, int nlat, int nlon) { 

double num, max; 
double latpos, lonpos; 

max = 0; 

for (int i=0; i<nlat; i++) { 
    for (int j=0; j<nlon; j++) { 
    num = elev[i][j]; 
    if (num > max) { 
     max=num; 
     latpos= ilat - i; 
     lonpos= ilon + j; 
    } 
    } 
} 

cout << "The tallest peak on earth has an altitude of " << max; 
cout << " and is located at " << latpos << "deg latitude and "; 
cout << lonpos << "deg longitude"; 

return max; 
} 

그러나, 나는 다음과 같은 오류가 함수를 호출 할 때 find_max (double (*) [3600], double, double, int, int) '에 인수'1 '에 대해 double (*) [3600]

+0

lon_col = 3600? – tmpearce

답변

0

크기가 동적으로 (즉 런타임에) 결정된 배열을 전달하려고하고 배열의 두 번째 차원이 컴파일 타임에 3600으로 결정될 것으로 기대하는 함수로 전달하려고합니다. 꽤 합리적인 것 불평하는 것, 실제로).

1

코드에서 볼 수 있듯이 몇 가지 결함이 있습니다.

  • 당신은

    으로 배열 높이를 정의

    이중 높이 [lat_row] lon_col];

C 스타일 배열의 크기가 컴파일 타임에 결정 가능해야하기 때문에 작동하지 않을 것입니다. lat_row와 lon_col은 변수이므로 오류입니다.

따라서 동적 메모리 할당 또는 std :: vector를 사용하여 배열을 사용할 수 있습니다. 대부분의 경우이 것이 좋습니다. 따라서 귀하의 경우에는 다음과 같은 것을 가질 수 있습니다 :

typedef std::vector< std::vector<double> > ElevationsType; 
ElevationsType elevations; 

그런 다음이 어레이 또는 배열을 사용하십시오. 당신이 단지 수 있기 때문에,이 경우에 당신이 nlat 및 nlon 통과해야되지 않습니다

double find_max(const ElevationsType &elevations, double ilat, double ilon); 

주 : 이 그런 다음 find_max 기능은 다음과 같이 선언 할 수

물론
ElevationsType::size_type nlat, nlon, i, j; 
nlat = elevations.size(); 

for (i = 0; i != nlat; ++i) { 
    nlon = elevations[i].size(); 
    for (j = 0; j != nlon; ++j) { 
     const double element = elevations[i][j]; 
     // do whatever you need to do with the element 
    } 
} 

, 배열이 고정 된 크기를 가지면 ElevationsType 유형의 객체를 생성하거나 충분한 공간 (std :: vector :: reserve)을 할당 한 다음 초기화하면 설정 (std :: vector :: resize) 할 수 있습니다. 크기가 클 경우 성능이 향상 될 수 있습니다. 말하자면 .. 많은 사람들이 더 지루한

double **elevations = (double **)malloc(sizeof(double*) * lat_row); 
for (size_t i = 0; i != lat_row; ++i) { 
    elevations[i] = (double*)malloc(sizeof(double) * lat_col); 

    // initialize the elements 
    for (size_t j = 0; j != lat_col; ++j) { 
     elevations[i][j] = 100.0; /* your value */ 
     std::cout << "elevations[" << i << "][" << j << "] = " << elevations[i][j] << std::endl; 
    } 
} 

: 당신은 C 스타일 배열을 이동하도록 선택하는 경우

그러나,이 같은 것을 할 것이다. 그리고 그 경로에 있다면 free()를 사용하여 할당 된 메모리를 모두 할당 해제하는 것을 잊지 마십시오.

또한 C++ new 연산자를 사용하여 메모리를 할당 할 수도 있지만 원리는 거의 같습니다.

그래서 std :: vector를 사용하는 것이 좋습니다. 적어도 경험이 적은 경우에는 작업하기가 더 쉽습니다. 또한 메모리 할당/할당 해제를 처리 할 것이고, 이는 많은 나쁜 일, 오버 플로우, 누수 등을 야기합니다. 벡터를 사용하면 피할 수 있습니다.

+0

답변 해 주셔서 감사합니다. 프로그램 변수 대신 정수 값을 사용하여 배열 크기를 설정하자마자 호출 함수가 정상적으로 작동한다는 것을 알게되었습니다. 나는 여전히 C++에 조금 익숙하지 않으며 과거에는 벡터를 사용하려고했지만 완전히 익숙하지 않습니다. 이것은 더 좋은 기회가 될 것 같습니다! – user1263011

+0

예, C 스타일 배열 (포인터 등)을 사용하는 데 따르는 어려움을 피하기 위해 "std :: vector"를 사용하십시오. 그래도 여전히 유용한 (C 스타일 배열) 알고 있고, 시간이 있다면 주제에 대한 기사가 많이 있습니다. 초보자를위한이 포럼의 최근 게시물 2 개를 참조하십시오. http://stackoverflow.com/questions/9583086/2dimensional-array-pointer-manipulation-in-c/9608139#9608139 및 http://stackoverflow.com/questions/9672731/manipulating-multidimensional-arrays-with-functions-in-c/9677552 # 9677552 – Larry

관련 문제