2017-04-09 176 views
0

我收到錯誤:從int到int的無效轉換*

從int到int *的轉換無效。

我還沒有創建任何int *(我認爲),當我將有問題的行更改爲int *時,沒有生成錯誤,但程序在啓動時崩潰。

這裏是我的代碼:

//Main: 
int main(){ 

    //Varibales: 
    Random randomInt; 
    clock_t start; 
    clock_t End; 
    double duration; 
    double clocksPerSec; 
    int result; 
    int arraySize; 


    //Repeat 100 times: 
    for(int i=1; i<=100; i++){ 

     //Set array size: 
     arraySize = i*500; 
     //Create the array: 
     int testArray[arraySize]; 

     //For the array size: 
     for(int j=0; j<arraySize; j++){ 


      //Add random number to array: 
      testArray[j] = randomInt.randomInteger(1, 10000); 

     } 

     //Run the test: 
     start = clock(); 
     result = algorithmTest(testArray[arraySize], arraySize); 
     End = clock(); 

     //Calculate execution time: 
     duration = End - start; 
     clocksPerSec = duration/CLOCKS_PER_SEC; 

     //Display the result: 
     cout << "The median is: "; 
     cout << result << endl; 
     cout << "Exection time was: "; 
     cout << clocksPerSec; 
     cout << "s\n" << endl; 

    } 

    //Return 0: 
    return 0; 

} 

它接縫我的呼喚algorithmTest()將引發錯誤;那就是:

//First Test: 
int algorithmTest(int testArray[], int Size){ 

    //Declare variables: 
    int k = Size/2; 
    int numSmaller; 
    int numEqual; 

    //For every element in the array: 
    for(int i=0; i<Size; i++){ 

     //Set varibales to 0: 
     numSmaller = 0; 
     numEqual = 0; 

     //For every element in the array: 
     for(int j=0; j<Size; j++){ 

      //If j is less than i: 
      if(testArray[j] < testArray[i]){ 

       //Increment numSmaller: 
       numSmaller++; 

      //Else if j is equal to i: 
      }else if(testArray[j] == testArray[i]){ 

       //Increment numEqual: 
       numEqual++; 

      } 
     } 

     //Determine if the median was found: 
     if(numSmaller < k && k <= (numSmaller + numEqual)){ 

      //Retrun the medain: 
      return testArray[i]; 

     } 
    } 

    //Return 0: 
    return 0; 

} 

回答

1
result = algorithmTest(testArray[arraySize], arraySize); 

應該

result = algorithmTest(testArray, arraySize); 

你的功能int algorithmTest(int testArray[], int Size)需要一個int[]作爲第一個參數,而你傳遞一個testArray[arraySize],其中[i]運營商指的ith元素獲取值testArray,這是一個int。因此你遇到那個錯誤。

爲了澄清一些,在線路int testArray[arraySize];[...]距離[...]不同的線result = algorithmTest(testArray[arraySize], arraySize);:第一種是用於指示數組的大小,而第二個是用於訪問的元素。

0

看看AlgorithmTest的定義。你需要一個int [](也被稱爲int *)作爲第一個參數,但是當你調用它的時候,你會給它一個實際的int