Is it safe to read the end of an array?

Let's say I have a constructor like this:

MyColor(uint8 vec[]) {
r = vec[0];
g = vec[1];
b = vec[2];
a = vec[3];
}

But I call it that (3 elements instead of 4):

uint8 tmp[] = {1,2,3};
MyColor c(tmp);

But now vec[3]there is undefined ... is it safe to assign this value a? If not, is there a suitable workaround to check if it is installed vec[3]?

+3
source share
8 answers

If you do not want to use a vector, try this ...

MyColor(uint8 (&vec)[3])
{
   r = vec[0];
   g = vec[1];
   b = vec[2];
}

MyColor(uint8 (&vec)[4])
{
   //...
}

uint8 a1[] = {1,2,3};
MyColor c1(a1);
uint8 a2[] = {1,2,3,4};
MyColor c2(a2);
uint8 a3[] = {1,2,3,4,5};
MyColor c3(a3); // error

you do not need to explicitly specify the size of the array, and if you try to pass an array with the wrong number of elements, a compilation error will be generated,

+3
source

, . undefined, . . , vector.

+19

, . , , undefined. .

"" , , , , . :

uint8 tmp[4] = {1,2,3};
MyColor c(tmp);

, . .

+13

, . , :

MyColor(uint8 a, uint8 b, uint8 c, uint8 d) {
    stuff
}

MyColor(uint8 a, uint8 b, uint8 c) {
    stuff
}

MyColor a(1, 2, 3);
MyColor b(1, 2, 3, 4);
+4

++, C, . , , :

// explicit parameters (with or without default values):
mycolor( uint8_t r, uint8_t g, uint8_t b, uint8_t alpha = 255 );

// vector (can check length)
mycolor( std::vector<uint8_t> const & components );

// array by reference
mycolor( uint8_t (&components)[ 4 ] );

- .

+2

. , segfault.

Billy3

+1

undefined , , .

vector:: at(). , . ,

+1

, , . .

, .

, , .

0

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


All Articles