I am getting this error:
The variable "thename" is being used without being initialized
Here's my code:
char *thename;
cm++;
sprintf(thename, "tutmap%d.map", cm);
I am getting this error:
The variable "thename" is being used without being initialized
Here's my code:
char *thename;
cm++;
sprintf(thename, "tutmap%d.map", cm);
You are using the variable without initializing it, and running this code will be Undefined Behavior.
Perhaps you meant:
char thename[42];
cm++;
sprintf(thename, "tutmap%d.map", cm);
If you have snprintf, here's a function which documents that you guarantee ("assert") the buffer to be large enough, but then also checks the buffer length and aborts if you made an error:
template<int N>
void fixed_sprintf(char (&array)[N], char const *format, ...) {
va_list args;
va_start(args, format);
int used = vsnprintf(array, N, format, args);
va_end(args);
if (used == N - 1) {
throw whatever_exception_type_you_like("buffer too small");
// or even:
abort();
}
}
The "fixed" means "fixed-size", not "opposite of broken". :)
You've declared a pointer to a C string but not allocated any memory for it.
If you want stack allocated memory use
char thename[buffer_length];
If you prefer heap allocation use
char *thename = malloc(buffer_length);
I know the question is tagged C++ but your code looks more like C to me. Hence the use of malloc.
Instead of writing:
char *thename;
cm++;
sprintf(thename, "tutmap%d.map", cm);
Write:
cm++;
std::stringstream stream;
stream << "tutmap" << cm << ".map";
std::string const name = stream.str();
// and if you really need char* then:
char const* thename = name.c_str();
char const* thename = name.c_str();. It makes the code hard to maintain as you have an implicit requirement (that is not documented) that name can not be modified (or read in some cases (name[0] may cause a copy in COW implementations)) without thename becoming invalid. The only time it is safe to use c_str() is when you pass it as a parameter to a function.name const as well.char *thename = new char[21]; //21 is used for maximum string length of 20
cm++;
sprintf(thename, "tutmap%d.map", cm);