0

I would like to perform the above mentioned operation, however I would like to make sure that the char array is exactly the same size with the string at hand.

So the real question is, how can I make an array with a size that is going to be determined in the run time?

0

6 Answers 6

5

allocating memory on the free store, and copying the string in one go:

std::string s("abcdef");

...
char* chars=strdup(s.c_str());

You need to free the memory manually, of course. Documentation e.g. on the man page. As @Loki mentions: freeing this memory is done through free(chars), not through delete. Also, you need to include the <cstring> header.

If you want to stay in the c++ world, use a vector; it can be created with two iterators to copy it's data from, and will allocate on the heap, and will cleanup by itself. Isn't that a treat?

std::vector<char> vec( s.begin(), s.end() );
Sign up to request clarification or add additional context in comments.

3 Comments

Now you have to pepper your code with free(). So it saves you one line here but makes the code much more complex as you have two different memory pools to manage.
@LokiAstari: that is very true. I should have added that - personally I prefer the vector approach, though.
Also, note that the OP said "make sure that the char array is exactly the same size with the string at hand"; if the string contains embedded null characters, then your std::vector<> solution will work properly while your strdup solution will not.
3

You can create an array of size known at runtime with the "new" operator:

char* res = new char[str.size()+1];
strncpy(res, str.c_str(), str.size()+1);

1 Comment

If the string contains any embedded null characters then strncpy will truncate the data. memcpy is more appropriate here, or a proper container such as std::vector<>.
2
std::string s = "hello";
char* c = new char[s.length() + 1]; // '+ 1' is for trailing NULL character.

strcpy(c, s.c_str());

Comments

1
#include <string>

int main(int argc, char *argv[])
{
   std::string random_data("This is a string");

   char *array=new char[random_data.size()+1];

   // do stuff

   delete[] array;

   return 0;
}

Comments

1

Try:

char* res = new char[str.size()+1]();   // Note the () makes sure it is '0' filled.
std::copy(str.begin(), str.end(), res); // Don't need to copy the '\0' as underlying
                                        // array already has '\0' at the end position.
...
delete [] res;                          // Must not forget to delete.

Or: (preferably)

std::vector<char> res(str.begin(), str.end());

Or: If all you want to do is call a C-unction:

str.c_str()

Comments

-1

Use strlen() to find the length of the string, then malloc() a char array of that size.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.