请说到最后,再说:“哦,不,这个问题再次出现……”
我现在正坐在C课程中,并且在课本中提供了以下示例:
#include <stdio.h>
#include <stdint.h>
void Terminal_PrintData(uint16_t * const Data);
int main(void){
uint16_t StringData[] = "MyData";
Terminal_PrintData(StringData);
}
void Terminal_PrintData(uint16_t * const Data)
{
printf("Value: %s", *Data);
}
当我编译这个杰作时,我得到的是:
F:\AVR Microcontroller>gcc -o test test.c
test.c: In function 'main':
test.c:7:26: error: wide character array initialized from non-wide string
uint16_t StringData[] = "MyData";
我的问题是:
uint16_t
?您的直接问题:
- 用uint16_t声明字符串是否正确?
不。
所有的字符串都是永远的char[]
。也有宽字符串(宽字符的字符串),其类型为wchar_t[]
,并以L
前缀(例如L"hello"
)编写。
- 建议将字符串传递给函数的方法是什么?
作为指针以在字符串中的第一个字符,所以无论是char *
或wchar_t *
。const
此处的预选赛毫无意义。这意味着指针(而不是字符串本身)是常量(请参见此处)。我建议wchar_t const *
还是写const wchar_t *
;它有不同的含义(即字符串不能更改),但它是正确且有意义的。
您提到此代码来自一本教科书。我不确定您是说这些是您的教授分发的讲义,还是购买了已出版的书。无论哪种情况,如果该摘录都代表了书/笔记的质量,请退款。
现在,让我们使这段代码起作用。
这段代码中有一个错误,它将导致程序崩溃:
printf("... %s ...", ..., *string, ...)
当string
是一个char*
永远是错的。不要取消引用该指针。如果您坚持使用“宽”字符(这是可疑的),那么您将不得不进行一些更改:
char
无需使用,而是需要包含<wchar.h>
和使用wchar_t
。据我所知,uint16_t
并uint8_t
不会工作,除非你使用显式铸造无处不在。那是因为char
没有8位,而是CHAR_BIT
bits。L
前缀开头。printf
,您需要使用wprintf
。%ls
而不是%s
。(除非您使用Microsoft的编译器。)最后,一些不太严重的错误:
T * const
参数是没有用的。作者可能的意思是T const *
(或等效地const T *
)。<stdint.h>
和<stdio.h>
。我们不再使用uint16_t
,并<wchar.h>
声明了一些类似于字符<stdio.h>
的函数。我最终得到以下代码:
#include <wchar.h>
void Terminal_PrintData(wchar_t const * Data);
int main(void){
wchar_t StringData[] = L"MyData";
Terminal_PrintData(StringData);
}
void Terminal_PrintData(wchar_t const * Data)
{
wprintf(L"Value: %ls", Data);
}
它可以在Linux x86-64上与GCC和Clang一起编译并按预期运行。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句