Kryptomatrix Kryptomatrix - 3 months ago 10
C++ Question

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

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';
}


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;
}
int main()
{
}


Thank you for help

Answer

you should learn to use strncpy(str2, str1, len(str1)) and not strcpy, as strcpy is one of the most classically well known to be unsafe function in c/c++, as it can write past the end of the buffer, potentially a buffer overflow.