C语言 从 'uint8_t* {aka unsigned char*}' 到 'const char*' [-fpermissive] 的无效转换
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29643031/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
invalid conversion from 'uint8_t* {aka unsigned char*}' to 'const char*' [-fpermissive]
提问by Saim Neftci
I am writing code in C for STM32 with gcc compiler, I am tried suggestions. I am calling fuction from i2c.c via i2c.h definiton. May be I did mistake there. Thanks for comments.
我正在用 gcc 编译器为 STM32 编写 C 代码,我尝试了建议。我通过 i2c.h 定义从 i2c.c 调用函数。可能是我在那里弄错了。感谢您的评论。
(i2c.h)
(i2c.h)
#define Chip_TxBurst(wREG, wCNT, pbDATA) \
I2C_TxBurst((0xC0) | (((wREG) >> 7) & 0x1E), (wREG), (wCNT), (pbDATA))
(i2c.c)
(i2c.c)
void I2C_TxBurst (
uint16_t bSLA, /* I2C slave address */
uint16_t bREG, /* I2C sub-address */
uint16_t bCNT, /* The number of data which will be transmitted */
uint8_t *pbDATA /* Point to the first DATA item */
)
{
uint8_t bIdx;
for (bIdx = 0; bIdx < bCNT; bIdx++)
{
I2C_TxData(pbDATA[bIdx]);
} /* for */
} /* I2C_TxBurst */
(osd.c)
(osd.c)
void OSD0_TEXT( uint8_t *TEXT,
uint8_t FONT_SIZE_X,
......
)
{
Chip_TxBurst(0x400, FONT_SIZE_X, TEXT);
}
(main)
(主要的)
main{
OSD0_TEXT("STAY FOLISH",11);
}
##
(old question code)
(旧问题代码)
void OSD0_TEXT ( uint8_t *TEXT)
{
.....
TxBurst(0x400, strlen(TEXT), TEXT);
.....
}
main{
OSD0_TEXT("STAY FOLISH");
}
回答by Lundin
Strictly speaking, uint8_tand charmay not always be compatible, since charhas implementation-defined signedness and could be a signed type on some compilers.
严格地说,uint8_t而char不一定是兼容的,因为char有实现定义的符号性和可能是在某些编译器有符号的类型。
In practice, casting to/from uint8_tto/from charwill always work when charis used for storing ASCII characters, since there are no symbol tables with negative indices.
实际上,当用于存储 ASCII 字符时,to/from uint8_tto/from 转换char将始终有效char,因为没有带有负索引的符号表。
Side-notes:
旁注:
You should always strive for const correctness, especiallywhen creating pointers to string literals.
The size of string literals could be computed at compile-time, to save a little bit of time.
main() returns void on any bare metal ARM system I have ever seen. It does not return int, because that wouldn't make any sense (return to who?).
您应该始终争取 const 的正确性,尤其是在创建指向字符串文字的指针时。
字符串文字的大小可以在编译时计算,以节省一点时间。
main() 在我见过的任何裸机 ARM 系统上都返回 void。它不返回 int,因为那没有任何意义(返回给谁?)。
So the proper fix for your code is:
因此,您的代码的正确修复是:
void OSD0_TEXT (const uint8_t* TEXT, size_t size)
{
...
TxBurst(0x400, size, TEXT);
...
}
void main (void)
{
static const char STR[] = "STAY FOOLISH"; // static to ensure it wont end up in RAM
const size_t STR_LEN = sizeof(STR) - 1;
OSD0_TEXT((const uint8_t*)STR, STR_LEN);
}
回答by user2407394
void OSD0_TEXT ( const char *TEXT)
{
.....
TxBurst(0x400, strlen(TEXT), TEXT);
.....
}
main{
OSD0_TEXT("STAY FOLISH");
}

