制作指向两个字节的指针

2 c pointers i2c

除了可能呼吸,我是一个完整的新手,所以对不起,如果我不清楚,但这里是:

我在C中有一个函数,它通过I2C总线将字节写入电路,在头文件中它看起来像这样:

BOOL WINAPI JidaI2CWrite(HJIDA hJida, DWORD dwType, BYTE bAddr, LPBYTE pBytes, DWORD dwLen);
Run Code Online (Sandbox Code Playgroud)
  • hJida:董事会处理.
  • dwType:I2C总线的从零开始的数字.
  • bAddr:I2C总线上器件的地址,写入总线时的全部8位.
  • pBytes:指向包含字节的位置的指针.
  • dwLen:要写入的字节数.

如果我只想将一个字节写入地址为0x98的电路,我会这样做:

unsigned char writing[1];
writing[0]=0x10;

unsigned char *pointer;
pointer = &writing[0];


JidaI2CWrite(hJida,0,0x98,pointer,1);
Run Code Online (Sandbox Code Playgroud)

这似乎工作,但如果我想写两个字节,比如0x10FF,它不会.那么如何制作一个指向两个字节而不是一个字节的指针呢?

谢谢

Gab*_*abe 10

你想要这样的东西:

unsigned char writing[2];
writing[0] = 0x01;
writing[1] = 0x02;

JidaI2CWrite(hJida, 0, 0x98, writing, 2);
Run Code Online (Sandbox Code Playgroud)

请注意,C中的数组通常可以像指针一样使用.该变量writing可以被认为只是指向一块内存的指针,在这种情况下,该内存块的大小为2个字节.创建另一个指向该位置的指针是多余的(在本例中).

请注意,您可以指向任意数量的字节:

unsigned char writing[12];

//fill the array with data

JidaI2CWrite(hJida, 0, 0x98, writing, 12);
Run Code Online (Sandbox Code Playgroud)

  • "请注意,C中的数组实际上只是指针"并不完全......请参阅"http://www.lysator.liu.se/c/c-faq/c-2.html" (2认同)

Aut*_*act 6

试试这个...

//A buffer containing the bytes to be written
unsigned char writeBuffer[] = {0x10, 0xFF}; 

//writeBuffer itself points to the start of the write buffer
//you dont need an extra pointer variable
//Indicate the size of the buffer in the call to the function
//pointers do not carry array size information with them (in C/C++)
JidaI2CWrite(hJida,0,0x98,writeBuffer,2); 
Run Code Online (Sandbox Code Playgroud)

还是更好

unsigned char writeBuffer[] = {0x10, 0xFF};

JidaI2CWrite(hJida,0,0x98,writeBuffer
              ,sizeof(writeBuffer)/sizeof(unsigned char));
Run Code Online (Sandbox Code Playgroud)

注意:sizeof(writeBuffer)/sizeof(writeBuffer[0])为您自动计算数组的大小(以字节为单位)