Declaring the largest array using size_t

I wanted to declare a very large array. I found that the maximum size of the array is size_t, which is defined as UINT_MAX

so I wrote code like this

int arr[UINT_MAX];

when i compile this it talks about overflow in array size

but when I write like this:

size_t s = UINT_MAX;
int arr[s]; 

It compiles correctly. who cares

+3
source share
6 answers

First error: size_tnot necessary unsigned int, therefore its maximum value may differ from the value unsigned int( UINT_MAX); in addition, in C ++ you should use to get information about type boundaries std::numeric_limits.

#include <limits>

size_t s=std::numeric_limits<size_t>::max();

: ; size_t , , , , , , , , , ; , int, , , UINT_MAX*sizeof(int) , , , 4 - - , , sizeof(arr) wouldn 't , . .

, , , , , , ( ).

: . , , , , ( , , ).

++ , , , , VLA ( C99, ++). (VLA ), ( , , , VLA , VLA = > , , ).

: ( ), . , . , , .

+14

.

16 * , 32- .

- , , , .

, , .

*

+2
size_t s = UINT_MAX;
int arr[s];  

, s const. , UINT_MAX . . , .

0
size_t s = UINT_MAX;
int arr[s];

, arr (VLA). , ++. ,

g++ -ansi -pedantic -std=c++98

, arr UINT_MAX * sizeof( int ) . !

0

? V++ ( s const). , undefined, UINT_MAX * sizeof(int), , , , , .

0

-1. , 64-

unsigned char uchar_max = -1;
printf("%u\n", uchar_max);
unsigned int uint_max = -1;
printf("%u\n", uint_max);
unsigned long ulong_max = -1;
printf("%lu\n", ulong_max);
size_t sizet_max = -1;
printf("%lu\n", sizet_max);

:

255
4294967295
18446744073709551615
18446744073709551615
0

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


All Articles