Casting size_t to int to declare char array size

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

+4
source share
2 answers

size_t is an integer type, and no cast is required.

In C ++, if you want to have an array with dynamic size, you need to use dynamic allocation with new . That is, you cannot use:

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

Instead, you need to use the following:

 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 std::vector ( std::vector manages memory for you, so you don’t need to remember it explicitly, and you don’t need to worry about many of the ownership problems that come with dynamic allocation manually):

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

For more information on size_t, I highly recommend Dan Sachs's articles: “Why size_t matters” and “Further information on size_t”

0
source

Source: https://habr.com/ru/post/1312796/


All Articles