C++ 不允许返回一个完整的数组作为函数的参数。但是,您可以通过指定不带索引的数组名来返回一个指向数组的指针。

如果您想要从函数返回一个一维数组,您必须声明一个返回指针的函数,如下:

int * myFunction() { . . . }

另外,C++ 不支持在函数外返回局部变量的地址,除非定义局部变量为 static 变量。例如:

#include <iostream>
using namespace std;

int a[10] = { 10,20 };
char *GetCharArr()
{
    static char sss[20] = { 0 };
    sprintf_s(sss, "ABABXX%d", a[0]);

    cout << sss << endl;
    return sss;
}

int main()
{
    char *xxx;
    xxx = GetCharArr();
    printf("当前的字符串是:%s", xxx);
    system("PAUSE");
    return 0;
}

C++ 在函数中使用静态局部变量,让函数返回数组

另一个例子:

#include <iostream>
#include <ctime>
#include <cstdlib>

using namespace std;

// 要生成和返回随机数的函数
int *getRandom()
{
    static int  r[10];

    // 设置种子
    srand((unsigned)time(NULL));
    for (int i = 0; i < 10; ++i)
    {
        r[i] = rand();
        cout << r[i] << endl;
    }

    return r;
}

// 要调用上面定义函数的主函数
int main()
{
    // 一个指向整数的指针
    int *p;

    p = getRandom();
    for (int i = 0; i < 10; i++)
    {
        cout << "*(p + " << i << ") : ";
        cout << *(p + i) << endl;
    }

    return 0;
}

C++ 在函数中使用静态局部变量,让函数返回数组

相关文章:

  • 2022-02-02
  • 2022-12-23
  • 2021-06-08
  • 2022-12-23
  • 2022-12-23
  • 2021-11-13
  • 2021-09-16
  • 2022-12-23
猜你喜欢
  • 2021-05-26
  • 2021-10-24
  • 2022-12-23
  • 2022-12-23
  • 2021-06-22
相关资源
相似解决方案