在c ++

时间:2018-04-10 13:59:40

标签: c++

我想从主函数向另一个函数发送一个二维数组,我想返回一维数组。我不知道如何从C ++函数返回一个数组。当我为标量值(不是向量或数组)执行它时,它工作正常。但是对于阵列,我有问题。这是我的代码:

#include <iostream>
using namespace std;

float display(float n[3][2]);       // declare my function
int main()                          // main function
{
    float num[3][2] = {             // a dummy 2D array
        {3.3, 4.3},
        {9.3, 5.3},
        {7.3, 1.3}
        };
    float a[3];
    a = display(num);               // send array to display function   // line 13
    for(int i = 0;  i < 3; ++i)
    {
    cout << "reurned array is : " << a[i] << endl;
    }
    return 0;
}

float display(float n[3][2])        // define my function
{
    float b[3];
    cout << "Displaying Values: " << endl;
    for(int i = 0;  i < 3; ++i)
    {
        b[i] = n[i][0];
        for(int j = 0; j < 2; ++j)
        {
          cout << n[i][j] << " ";
        }
    }
    cout << endl;
    for(int i = 0;  i < 3; ++i)
    {
    cout << "actual array is : " << b[i] << endl;
    }
return b;               // line 39
}

这是我得到的错误:

/main.cpp||In function ‘int main()’
/main.cpp|13|error: incompatible types in assignment of ‘float’ to ‘float [3]
/main.cpp||In function ‘float display(float (*)[2])’
/main.cpp|39|error: cannot convert ‘float*’ to ‘float’ in return

1 个答案:

答案 0 :(得分:-1)

One possible solution is:

#include <stdio.h>

typedef float farray[3][2];

float *display(farray n);       // declare my function

int main()                          // main function
{
    farray num = {             // a dummy 2D array
        {3.3, 4.3},
        {9.3, 5.3},
        {7.3, 1.3}
        };
    float *a;
    int i;

    a = display(num);               // send array to display function   // line 13
    printf("returned array is: ");
    for(i = 0;  i < 3; ++i)
    {
        printf("%f ", a[i]);
    }
    printf("\n");
    return 0;
}

float *display(farray n)        // define my function
{
    static float b[3];
    int i;

    printf("Displaying Values: \n");
    for(i = 0;  i < 3; ++i)
    {
        b[i] = n[i][0];
        for(int j = 0; j < 2; ++j)
        {
            printf("%f ", n[i][j]);
        }
    }
    printf("\n");
    printf("actual array is : ");
    for(i = 0;  i < 3; ++i)
    {
        printf("%f ", b[i]);
    }
    printf("\n");
    return b;               // line 39
}