c++ - 如何将静态 const char 作为参数传递给函数?
问题描述
我有一个多次执行的函数,我只希望变量在第一次运行时声明一次,因为有一个完整的变量列表要检查,所以我曾经static const
在函数中声明这些变量。
我想将其中一个static const char
数组传递给从该函数中调用的函数。我尝试使用指针并通过引用传递,但我不断收到不兼容const char *
的参数类型错误,说与参数不兼容。
如何将静态 const char 数组传递给函数?在函数中声明它们对我来说没有意义,因为它是一个列表,并且这个函数应该只检查其中一个,当它作为参数传递时很容易做到这一点。
功能一:
void searchFunc(int numOfBytes, char msgtxt[]) {
static const char msg1[] = { 0x11, 0xFF };
static const char msg1resp[] = { 0x0066, 0x03, 0xFF, 0x55, 0x00, 0x83 };
static const char msg2[] = { 0x03, 0x00, 0x6A };
static const char msg2resp[] = { 0x00, 0x05, 0x42, 0x1A, 0x80, 0x5A };
if (num == 5) {
respond(msgtxt, 2, 4, msg1, msg1resp);
} else if (num == 6) {
respond(msgtxt, 2, 5, msg2, msg2resp);
}
}
有错误的函数 2 定义:
void respond(char msgtxt[], int startArr, int endArr, char commandmsg[], char responsemsg[]);
“const char*”类型的参数与“char *”类型的参数不兼容
解决方案
您不能将指针传递给采用const
指针的函数。
static const char msg1[] = { 0x11, 0xFF };
声明msg1
为 a const char*
,但respond()
采用 a char msgtxt[]
,即 achar*
作为参数。
所以,为了让它工作,你的respond
函数应该有签名
void respond(const char*, int, int, const char*, const char*);
作为一般规则:未修改的对象的引用和指针应该是const
. 这也适用于您的searchFunc()
:
void searchFunc(int numOfBytes, const char*msgtxt) { ... }
推荐阅读
- android - React-Native:尝试在 AndroidManifest.xml 中使用自定义 XML
- reactjs - 我可以在屏幕上的多个位置重用组件的单个实例以做出反应吗?
- reactjs - 如何查看 gatsby-plugin-offline 是否正常工作
- html - CSS flex 对齐按钮
- java - 我无法暂停 TTS(特别是 Earcon)
- javascript - 如何在 React 中强制重新渲染功能组件?
- javascript - 如何在文本区域内动态渲染数学符号?
- javascript - 无效的 Web 服务调用,参数缺失值:“档案”
- postgresql - 无法使用 text[] 数据类型创建表
- swift - 尝试重新创建 SwiftUI 列表演示时出现错误“无法推断复杂的闭包返回类型;添加显式类型以消除歧义”