【问题标题】:Value of memory changed without permission未经许可更改内存值
【发布时间】:2017-02-24 13:07:52
【问题描述】:

我有一个二维数组,当我第一次打印数组的数据时,日期打印正确,但其他时候 array[last][i] 的数据从 i = 0 到最后 - 1.

显然是逻辑错误,但我不明白原因,因为我复制并粘贴了for语句。所以... ¿C 更改数据?

我使用 gcc -std=c99,但在此之前我尝试使用 C++ 和 cout 语句。

This is the output screenshot

#include <stdio.h>

int main(int argc, char *argv[])
{
  unsigned int numero_jugaderes = 11;
  unsigned int numero = numero_jugaderes - 1;

  unsigned int p_a[numero];

  float p_aya[numero][numero];

  for (unsigned int i = 0; i <= numero; i++) {
    p_a[i] = i;
  }

  for (unsigned int i = 0; i <= numero; i++) {
    for (unsigned int j = 0; j <= numero; j++) {
      p_aya[i][j] = (float) (p_a[i] * p_a[j]) / 100;
      printf("%f\t", p_aya[i][j]);
    }
    puts("");
  }

  puts("\n");

  for (unsigned int i = 0; i <= numero; i++) {
    for (unsigned int j = 0; j <= numero; j++) {
      printf("%f\t", p_aya[i][j]);
    }
    puts("");
  }

  return 0;
}

【问题讨论】:

  • 这在技术上不是一个有效的 C++ 程序,因为 C++ 没有variable-length arrays
  • @user 我猜是相反的
  • 至于您的问题,请记住 X 元素数组的有效索引范围为 0X - 1(含)。现在仔细看看你的循环。
  • 请勿发文字图片。

标签: c arrays loops


【解决方案1】:

我看到的问题是,您正在循环使用类似的条件检查

 for (unsigned int i = 0; i <= numero; i++) 

对于定义为的数组

unsigned int p_a[numero];

你要去off-by-one。这本质上是调用undefined behavior 的无效内存访问。

C 数组具有从 0 开始的索引,因此有效限制为

for (unsigned int i = 0; i < numero; i++)

【讨论】:

    【解决方案2】:

    长度为 numero 的数组具有 numero 个元素。从索引 0 到 numero-1。你对待他们就像他们有一个索引号一样。将i &lt;= numero 切换为i &lt; numero。对所有 for 循环和 j 执行相同操作。

    【讨论】:

      【解决方案3】:

      如果您有一个声明为具有numero 元素的数组,则有效的索引范围是[0, numero-1]

      因此像这样的循环

      for (unsigned int i = 0; i <= numero; i++) {
      

      用于访问带有numero 元素的数组元素会导致未定义的行为。

      【讨论】:

        猜你喜欢
        • 2013-06-24
        • 2015-02-08
        • 1970-01-01
        • 2021-05-03
        • 1970-01-01
        • 2011-01-26
        • 2016-09-28
        • 2010-12-20
        • 2020-03-04
        相关资源
        最近更新 更多