将访问a \ 0&quot'在char阵列结束时,导致C中的不确定行为?

发布于 2025-01-24 07:58:27 字数 777 浏览 1 评论 0原文

在这个代码段中,有什么可能出错的吗?

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

染柒℉ 2025-01-31 07:58:27

“即使a的大小为5” - &gt; “ Araba”是大小

6

printf("%zu\n", sizeof("araba")); 

"even though the size of a is 5" --> "araba" is size 6.

Try

printf("%zu\n", sizeof("araba")); 

Reading a string literal's null character is fine.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文