casting size_t to int to declare size of char array
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开发者_JS百科 that I can do that?
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);
For more background on size_t, I strongly recommend Dan Saks articles: "Why size_t matters" and "Further insights into size_t"
精彩评论