【问题标题】:Change array I pass to function without Return in C更改我传递给函数的数组而不用 C 中的 Return
【发布时间】:2020-05-24 23:30:57
【问题描述】:

这是我的功能:

void eeprom_read_page(unsigned int address, unsigned char lengh, unsigned char *data[40])
{
    //unsigned char data[lengh] , i;
    unsigned char  i;
    i2c_start();
    i2c_write(EEPROM_BUS_ADDRESS_W);
    i2c_write(address>>8);          //high byte address
    i2c_write(address*0xff);        //low byte address
    i2c_start();
    i2c_write(EEPROM_BUS_ADDRESS_R);
    for(i=0 ; i<(lengh-1) ; i++)
    {
       *data[i+4]=i2c_read(1);
    }
    *data[lengh+3]=i2c_read(0);
    i2c_stop();
}

这就是我在代码中某处使用它的方式:

eeprom_read_page(   ( (rx_buffer1[1]*256)+rx_buffer1[2] ) , rx_buffer1[3] , &amp;tx_buffer1 );

这是我的数组定义:

#define RX_BUFFER_SIZE1 40
char rx_buffer1[RX_BUFFER_SIZE1],tx_buffer1[RX_BUFFER_SIZE1];

但是tx_buffer1 没有得到我在数据[] 中给出的值。我想更改tx_buffer1,但不要使用返回。有什么帮助吗?

【问题讨论】:

  • 显示数组是如何定义的。
  • Unsigned char data[40] 是一个由四十个字符组成的数组。不应该是 unsigned char data[40] 还是 unsigned char *data?
  • 来自莫斯科的@Vlad 已更新!
  • @barny 我试过了,但两者都出现 IDE 错误。
  • 要更改参数而不返回,您需要修改指针。这就是你的线索。

标签: c multidimensional-array avr implicit-conversion function-declaration


【解决方案1】:

数组声明方式如下

#define RX_BUFFER_SIZE1 40
char rx_buffer1[RX_BUFFER_SIZE1],tx_buffer1[RX_BUFFER_SIZE1];

用于表达式

&tx_buffer1

使表达式类型为char ( * )[RX_BUFFER_SIZE1]

同时对应的函数参数

unsigned char *data[40]

具有unsigned char ** 类型,因为编译器隐式调整具有数组类型的参数以指向数组元素类型对象的指针。

此外,函数参数使用说明符 unsigned char,而数组使用说明符 char 声明。

所以函数调用无效。指针类型之间没有隐式转换。

通过引用将数组传递给函数没有任何意义,因为在任何情况下数组都是不可修改的左值。

如果你想通过引用传递数组来知道它在函数中的大小,那么函数参数应该声明为

char ( *data )[40]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-19
    • 1970-01-01
    • 2021-12-27
    • 2021-05-23
    • 2020-12-15
    • 2015-12-14
    • 2012-07-25
    • 2011-11-08
    相关资源
    最近更新 更多