casting size_t to int to declare size of char array

Brandon Hilton picture Brandon Hilton · Jun 14, 2010 · Viewed 7.4k times · Source

I am trying to declare a size of a char array and I need to use the value of the variable that is declared as a size_t to declare that size. Is there anyway I can cast the size_t variable to an int so that I can do that?

Answer

James McNellis picture James McNellis · Jun 14, 2010

size_t is an integer type and no cast is necessary.

In C++, if you want to have a dynamically sized array, you need to use dynamic allocation using new. That is, you can't use:

std::size_t sz = 42;
char carray[sz];

You need to use the following instead:

std::size_t sz = 42;
char* carray = new char[sz];
// ... and later, when you are done with the array...
delete[] carray;

or, preferably, you can use a std::vector (std::vector manages the memory for you so you don't need to remember to delete it explicitly and you don't have to worry about many of the ownership problems that come with manual dynamic allocation):

std::size_t sz = 42;
std::vector<char> cvector(sz);