【问题标题】:Increment or decrement the value of an array index in C在 C 中增加或减少数组索引的值
【发布时间】:2013-10-31 01:13:08
【问题描述】:

我的代码如下所示:

int some_array[8];
some_array[7] = an_integer;
if ( 550 < some_value ) {
  some_array[7]--;
  log("Lowered the value");
}

我希望如果我在日志中看到字符串“Lowered the value”,我应该知道代码正在执行。但是,我看到了记录的字符串,但值没有改变。 some_array[7]-- 在 C 中是否有我缺少的东西?

【问题讨论】:

  • 为什么你认为你some_value 大于550?分配在哪里?
  • 这个编译吗...就像你有两个同名的变量一样。
  • @IlyaBursov 他看到了log("Lowered the value");,它在同一个if 语句中。
  • @IlyaBursov 它并不总是大于 550。但是,如果是我收到的日志消息表明该块已执行。
  • @ToothlessRebel 您可能想从第二行删除int 并尝试再次运行它...

标签: c arrays decrement


【解决方案1】:
int some_array[8];
int some_array[7] = an_integer;  //This is the problem line.
if ( 550 < some_value ) {
   some_array[7]--;
   log("Lowered the value");
}

这段代码没有做你认为它正在做的事情。

您没有具有 8 个索引的 some_arraysome_array 有 7 个索引,some_array[7] 超出了 some_array[] 实际持有的范围(但 C 不会为此抛出异常)。试试这个:

int some_array[8];
some_array[7] = an_integer;
if ( 550 < some_value ) {
   some_array[7]--;
   log("Lowered the value");
}

【讨论】:

  • 我什至不能用双重声明(GCC-4.8.1)编译它。
【解决方案2】:

试试这个

int some_array[8];
int some_array[7] = an_integer;

if ( 550 < some_value ) {
  some_array[7] = some_array[7]--;
  log("Lowered the value");
}

【讨论】:

  • int some_array[7] = an_integer; 问题很大。
  • some_array[7] = some_array[7]--;未定义的行为:您在同一序列点中修改了两次 some_array[7] 的值。 (尝试使用gcc -Wall 编译它会发出警告)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多