Reputation: 18171
I need to create a buffer that contains 300 symbols and pass it to the function described below:
void printThis(char *info);
What is the best way to generate this buffer?
If this is good:
char *buffer = new char()
then, how to add characters to this buffer? The following method is not good and it raises an access violation:
for (int i=0; i<300;i++)
{
sprintf(s,"%s",'a');
}
Upvotes: 0
Views: 253
Reputation: 146910
if this is good:
It isn't. It really, really, isn't. It's not even a buffer. Nor is this even close to a good idea.
std::string s;
for(int i = 0; i < 300; i++)
s.push_back('a'); // good job all round
std::cout << s; // 300*a. Why? Who knows?
printThis(s.c_str());
Upvotes: 0
Reputation: 254451
std::vector<char> buffer(300, 'a');
// I'm guessing that printThis wants a zero-terminated string
buffer.push_back(0);
printThis(&buffer[0]);
If you're using the C++11 library, then buffer.data()
might look nicer than &buffer[0]
.
If you really want to manage the memory yourself (hint: you don't), either create an automatic array:
char buffer[300];
or a dynamic array:
char * buffer = new char[300];
// Don't forget to delete it, and hope than nothing threw an exception
delete [] buffer;
Upvotes: 4