首页 > 解决方案 > 如何将静态 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 *”类型的参数不兼容

标签: c++

解决方案


您不能将指针传递给采用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) { ... }

推荐阅读