Brandon Hilton
Brandon Hilton

Reputation: 51

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 that I can do that?

Upvotes: 4

Views: 8148

Answers (2)

Chris Morlier
Chris Morlier

Reputation: 360

For more background on size_t, I strongly recommend Dan Saks articles: "Why size_t matters" and "Further insights into size_t"

Upvotes: 0

James McNellis
James McNellis

Reputation: 355049

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);

Upvotes: 7

Related Questions