无法转换' int *'到'浮动*'争论' 1'

时间:2017-12-10 21:55:38

标签: c++ arrays c++11 pointers

我使用指针

将整数数组复制到float数组中
// Copy This code into main.cpp file

#include <iostream>

using namespace std;

int main()

{

    int array1[5];

    int array2[7];

    float array3[5];

    int x;

    cout << "Enter 5 values :" << endl;
    for ( int i = 0; i < 5; i++ )
        {
            cin >> array1[i];
        }

        cout << "Enter 7 values :" << endl;
        for ( int j = 0; j < 7; j++ )
        {
            cin >> array2[j];
        }

    cout << "Please choose an option from the list : " << endl
     << "\t 1. integer array copy " << endl
     << "\t 2. float array copy " << endl
     << "\t 3. delete single row of array " << endl
     << "\t 4. delete block of  rows into array " << endl
     << "\t 5. add a row into the array " << endl
     << "\t 6. add block of rows into array " << endl
     << "\t 7. Quit " << endl;

    cin >> x;

    if ( x == 1 )

    {

        int *z = arrayCopy ( array1, 5, array2, 7 );

        for ( int i = 0; i < 12; i++){

            cout << z[i] << " ";

         }

        cout << endl ;

    }

    else if ( x == 2 )

    {

        float *z = floatArrayCopy ( array1, 5, array2, 7 );

        for ( int i = 0; i < 12; i++){

            cout << z[i] << " ";

         }

        cout << endl;

    }

    return 0;

}


// And copy this code into "arrayUtil.h" file

int *arrayCopy( int *a, int size1, int *b, int size2)

{

    int *c = new int[size1 + size2];

    for ( int i = 0; i < size1; i++)

    {

        c[i] = a[i];

    }

    for ( int i = 0; i < size2; i++)

    {
        c[size1 + i] = b[i];
    }

    return c;
}

float *floatArrayCopy( float *a, int size1, float *b, int size2)

{

    float *c = new float[size1 + size2];

    for ( int i = 0; i < size1; i++)

    {

        c[i] = a[i];

    }

    for ( int i = 0; i < size2; i++)

    {
        c[size1 + i] = b[i];

    }

    return c;

}

它给出错误..我改变了参数值以及指针类型但仍然给出问题..需要知道为什么???

提前致谢.. :))

1 个答案:

答案 0 :(得分:2)

问题在于呼叫

float *z = floatArrayCopy ( array1, 5, array2, 7 );

其中array1array2int的数组(因此将转换为指向int的指针 - 即int *)与函数定义< / p>

float *floatArrayCopy( float *a, int size1, float *b, int size2);

传递指针时,指针类型必须匹配 - float *int *不匹配。

C ++编译器会诊断出这一点,并给出反映上述内容的错误消息。

您的案例中的解决方案是将float的数组传递给函数,而不是int的数组。