修改 const char 参数

gle*_*mau 1 c++ constants char

我目前正在编写一个函数,该函数应该将多个字符保存到 const char* 中,const char* 是该函数的参数。总体功能已给出,我无法更改参数。大致如下:

bool charChange(const char* array, uint32_t length)
{
  for(uint32_t i = 0; i<length; i++){
    int32_t nextChar = getChar(); //Get next character. Needs to be signed int, for other logic
    array[i] = (char) nextChar;
  }
  return true;
}
Run Code Online (Sandbox Code Playgroud)

为了清楚起见,省略了一些逻辑,但这应该会突出问题。我尝试过各种黑魔法,但我不知道如何将字符传递给 const char 数组参数。说实话。这根本就没有道理。

Ted*_*gmo 8

有一个应该改变输入的函数将输入视为 是完全令人困惑的const。它没有任何意义。

无论如何,你可以const放弃const_cast

bool charChange(const char* array, uint32_t length) {
    for (uint32_t i = 0; i < length; i++) {
        int32_t nextChar = getChar();
        const_cast<char*>(array)[i] = static_cast<char>(nextChar);
    }
    return true;
}
Run Code Online (Sandbox Code Playgroud)

演示

注意:如果您传递给此函数的实际数组已声明const,则这将具有未定义的行为。