zoukankan      html  css  js  c++  java
  • 在QT函数中返回一个数组/把一个数组传参给函数

    1.把数组传参给函数
    可以定义一个QVector的一个数组
    QVector<int> num(10);
    for(int  i =0;i<10;i++)
    num [i] = i*i;
    fun(num); //直接传参数给fun(函数)

    void fun(QVector<int> num)
    {
       for(int i = 0;i<10;i++)
        qDebug()<<num[i];
    }

    2.函数返回一个数组

    首先在c++中是不允许数组作为函数的返回值的 

    在我刚开始使用返回数组时,直接返回去一个数组,让一个指针去接收,如下:(错误的写法)

    int* mainWindow::data()

    {

       int  tx[] = {    //要发送的数据数组
                            0xA2, 0x00, 0x00,
                            0xA2, 0x00, 0x00,
                            0xA2, 0x00, 0x00,
                            0xA2, 0x00, 0x00,
                            0xA2, 0x00, 0x00,
                            0xA2, 0x00, 0x00,
                            0xA2, 0x00, 0x00,
                            0xA2, 0x00, 0x00,
                            0xA2, 0x00, 0x00,
                            0xA2, 0x00, 0x00,
                       };

     return  tx;

    }

    然后用指针接收

    int *p = data();

    qDebug()<<p[0];

    发现在运行的时候会出现段错误,发现很多C语言都是这样写的,并没有错。

    后来发现c++中是不允许数组作为函数的返回值的 

    正确的做法是:

    #define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
    int* mainWindow::data()
    {
       int  tx[] = {    //要发送的数据数组
                            0xA2, 0x00, 0x00,
                            0xA2, 0x00, 0x00,
                            0xA2, 0x00, 0x00,
                            0xA2, 0x00, 0x00,
                            0xA2, 0x00, 0x00,
                            0xA2, 0x00, 0x00,
                            0xA2, 0x00, 0x00,
                            0xA2, 0x00, 0x00,
                            0xA2, 0x00, 0x00,
                            0xA2, 0x00, 0x00,
                       };
    
      int* temp = new int[ARRAY_SIZE(tx)];
      for ( int i =0; i < ARRAY_SIZE(tx); i++)
      temp[i] = (int)rx[i];
       return temp;
    }
    
    int  *p = data();
    qDebug()<<p[0];
    delete p;
  • 相关阅读:
    [转]数据类型和Json格式
    maven 配置阿里云仓库
    maven windows 环境变量
    jdk windows环境变量
    springcloud hystrix 部分参数整理
    springboot 解决 woff2、ttf 跨域无法解析问题
    centos7 mysql5.7 rpm 安装
    centos7.3 chrome 安装
    springboot 1.5.X junit测试
    centos7 配置ftp访问
  • 原文地址:https://www.cnblogs.com/wxh-53919/p/10709140.html
Copyright © 2011-2022 走看看