通过数组末尾读取是否安全? [英] Is it safe to read past 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];
}
但是我这样称呼它(3个元素而不是4个元素):
But I call it like this (3 elements instead of 4):
uint8 tmp[] = {1,2,3};
MyColor c(tmp);
但是现在vec[3]
是不确定的...将此值分配给a
是否安全?如果没有,没有很好的解决方法来检查是否设置了vec[3]
?
But now vec[3]
is undefined... is it safe to assign this value to a
? If not, there's no nice workaround to check if vec[3]
is set is there?
推荐答案
如果您不想使用矢量,请尝试此...
if you dont want to use 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 dont have to include the array's size explicitly and if you try to pass an array with wrong number of elements, compile error will be generated,
这篇关于通过数组末尾读取是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文