views:

144

answers:

2

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?

+6  A: 

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);
James McNellis
Minor detail, but shouldn't you be using delete [] in your example, when you use new []?
Jacob
@Jacob: Yes, and that's another excellent reason to use `std::vector`. :-) (Fixed and thanks)
James McNellis
A: 

For more background on size_t, I strongly recommend Dan Saks articles: "Why size_t matters" and "Further insights into size_t" (the first is referenced by the second)

Chris Morlier