说明:近期做项目遇到一个基础问题,就是传参,借此机会记录一下
1、需求
将数组传入函数,函数中改变其内容,并影响原来的值;
初始化字符串空间;
2、代码实现
spi.cpp
/* *功能:读取SPI通道n(指令决定) times次,获取平均值 *参数:buff为SPI读取指令,recv为接收的数据,times为读取次数 *返回值:空 */ void Thread_SPI::SPI_ReadWriteTimesAverage(const uint8_t *buff,int *recv, int times) { uint8_t str[times][2]; uint16_t str_16[times]; int voltage[10]; memset(str_16,0,times*sizeof(uint16_t));//初始化字符串空间 for(int i=0;i<times;i++) { SPI_ReadWriteByte(buff,&str[i][0],2);//发送命令开启通道2,读取数据 str_16[i] = str[i][0]; str_16[i] = str_16[i]<<8; str_16[i] |= str[i][1]; //qDebug()<<"采集的数值="<<QString("%1").arg(str_16[i]); voltage[i] = QString("%1").arg(str_16[i]).toInt(); } *recv = Bubble_Sort(voltage,times); //qDebug()<<"平均值="<<*recv; } /* *功能:读取SPI通道 *参数:buff为SPI读取指令,recv为接收的数据 *返回值:空 */ void Thread_SPI::SPI_ReadWriteByte(const uint8_t *buff,uint8_t *recv,int size) //Sixteen serial clock cycles are required to perform the conversion process //and to access data from the AD7888. //AD7888执行转换过程和访问数据需要16个时钟周期,两条指令 { // for(int i=0;i<size;i++) // qDebug("buff[%d]=%x",i,*(buff+i)); int ret; struct spi_ioc_transfer tr[2];//spi数据发送结构体 memset(&tr,0,2*sizeof(struct spi_ioc_transfer));//赋初值 //uint8_t tx[] ={ 0x80,0x00 };//AD7888,8位控制位,最高位为0、1无所谓 //为spi数据发送结构体赋值 tr[0].tx_buf = (unsigned long)buff;//发送数据 tr[0].rx_buf = (unsigned long)recv;//接收数据 tr[0].len = size; tr[0].delay_usecs = 0; tr[0].speed_hz = Speed; tr[0].bits_per_word = Bits; ret = ioctl(m_fd, SPI_IOC_MESSAGE(1), &tr ); if (ret < size ) { qFatal("can't send spi message"); } }
main.cpp
int main() { SPI_ReadWriteTimesAverage((uint8_t []){0x0c,0x0c},&voltage_int,10); }
3、C语言和C++传参的方式
C语言传参:(1)按值传递 (2)指针传递
C++传参: (1)按值传递 (2)指针传递 (3)引用传递
指针传参例子:
void SwapByPoint(int *x,int *y) { int temp = *x; *x = *y; *y = temp; } int main() { int x=3,y=5; wapByPoint(&x,&y);
/*如果这里使用 SwapByPoint(x,y) 则报错:cannot convert parameter 1 from 'int' to 'int *' */ return 0; }
引用传参例子:
void SwapByReference(int &x,int &y) { int temp = x; x = y; y = temp; } int main() { int x=3,y=5; SwapByReference(x,y); /*如果这里用SwapByReference(&x,&y) 则报错 cannot convert parameter 1 from 'int *' to 'int &' */ }