将访问a \ 0&quot'在char阵列结束时,导致C中的不确定行为?
在这个代码段中,有什么可能出错的吗?
int min(int x, int y, int z) {
if (x < y) {
if (x < z)
return x;
else
return z;
} else if (y < z) {
return y;
} else
return z;
}
int d(char* a, char* b, int n, int m) {
if (n == 0)
return m;
if (m == 0)
return n;
if (a[n-1] == b[m-1])
return d(a, b, n-1, m-1);
return 1 + min(d(a, b, n, m-1), d(a, b, n-1, m),d(a, b, n-1, m-1));
}
int main() {
printf("%d ", d("1111", "1100", 4, 4));
printf("%d ", d("01", "1100", 2, 4));
printf("%d", d("araba", "aba", 6, 3)); /// here
}
请注意,在最后一个函数上,函数给出的char阵列的大小比应有的要多。
因此
,即使a
是5
。代码>最后;因此,尽管不确定,但这不是范围访问。
这是一个在考试中为选择人员参加计算机奥林匹克营地的一个问题,并因未给出的原因而被取消。我在想那是正确的电话,谢谢。
In this snippet of code, is there anything that could go wrong?
int min(int x, int y, int z) {
if (x < y) {
if (x < z)
return x;
else
return z;
} else if (y < z) {
return y;
} else
return z;
}
int d(char* a, char* b, int n, int m) {
if (n == 0)
return m;
if (m == 0)
return n;
if (a[n-1] == b[m-1])
return d(a, b, n-1, m-1);
return 1 + min(d(a, b, n, m-1), d(a, b, n-1, m),d(a, b, n-1, m-1));
}
int main() {
printf("%d ", d("1111", "1100", 4, 4));
printf("%d ", d("01", "1100", 2, 4));
printf("%d", d("araba", "aba", 6, 3)); /// here
}
Note that on the last function call the size of the char array given to the function is one more than what it should be.
So essentially
a[5]
is accessed, even though the size of a
is 5.
What I know is since char pointer to string literal has /0
at the end; so although not sure, this is not out of bounds access.
This was a question that has been given on a test for choosing people for a computer olympiad camp and was cancelled for a reason not given. I was thinking if that was the right call, thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
“即使a的大小为5” - &gt;
“ Araba”
是大小6
。
"even though the size of a is 5" -->
"araba"
is size 6.Try
Reading a string literal's null character is fine.