C++ char[100] = "hello" doesn't work

时间:2016-08-31 18:15:51

标签: c++

Is there a better, shorter, easier to read version of the following code:

char ar[100];

int main() {
    //ar = "hello"; doesn't compile
    ar[0] = 'h';
    ar[1] = 'e';
    ar[2] = 'l';
    ar[3] = 'l';
    ar[4] = 'o';
    ar[5] = '\x00';
    return 0;
}

Note: The type of ar has to be char[100]. The "real" program is:

#include <string>
#include <cstdarg>

#define TO_STRING_BUF_SIZE 100

char toStringBuf[TO_STRING_BUF_SIZE];

std::string toCptr_(const char * format, ...) {
  va_list argzeiger;
  va_start(argzeiger, format);
  int16_t ret = vsnprintf(toStringBuf, TO_STRING_BUF_SIZE, format, argzeiger);
  if(ret >= TO_STRING_BUF_SIZE - 1) {
    //toStringBuf = "buffer too small";
  } else if(ret < 0) {
    //toStringBuf = "encoding error";
  }
  va_end(argzeiger);
  std::string returning(toStringBuf);
  return returning;
}

3 个答案:

答案 0 :(得分:6)

Use the strcpy function to copy a C-style string.

strcpy(ar, "hello");

答案 1 :(得分:0)

正如其他人所说,您可以使用strcpy() / strncpy()将字符串复制到char[]缓冲区。

但是,在这个例子中实际上并不需要。您的函数返回std::string,因此您根本不需要char[]。对于短消息,长消息的限制和线程不安全的情况(除非使用本地缓冲区而不是全局缓冲区),这是浪费内存。试试这个:

#include <string>
#include <cstdarg>

std::string toCptr_(const char * format, ...)
{
    std::string str;

    va_list argzeiger;
    va_start(argzeiger, format);

    int ret = vsnprintf(NULL, 0, format, argzeiger);
    if (ret < 0) {
        str = "encoding error";
    }
    else {
        str.resize(ret+1);
        vsnprintf(&str[0], str.size(), format, argzeiger);
        str.resize(ret);
    }

    va_end(argzeiger);

    return str;
}

或者,至少:

#include <string>
#include <cstdarg>

#define TO_STRING_BUF_SIZE 100

std::string toCptr_(const char * format, ...)
{
    char toStringBuf[TO_STRING_BUF_SIZE];
    std::string str;

    va_list argzeiger;
    va_start(argzeiger, format);

    int ret = vsnprintf(toStringBuf, TO_STRING_BUF_SIZE, format, argzeiger);
    if (ret < 0) {
        str = "encoding error";
    }
    else if (ret < TO_STRING_BUF_SIZE) {
        str.assign(toStringBuf, ret);
    }
    else {
        str.resize(ret+1);
        vsnprintf(&str[0], str.size(), format, argzeiger);
        str.resize(ret);
    }

    va_end(argzeiger);

    return str;
}

答案 2 :(得分:-1)

Use strncpy(), eg:

strncpy(toStringBuf, str_buf, TO_STRING_BUF_SIZE);
toStringBuf[TO_STRING_BUF_SIZE-1] = 0;

Don't use strcpy(), as it is one of the most classically well-known unsafe functions in C/C++. It can write past the end of the buffer, causing buffer overflow errors. Not a problem in your particular example, but it should still be avoided in general.