【问题标题】:Where would you add the +1 when dealing with arrays?处理数组时,您会在哪里添加 +1?
【发布时间】:2017-05-11 12:49:22
【问题描述】:

由于数组从零开始而不是从一开始,我想在我的代码中明确说明我将向计数器 (i) 添加一来弥补这一点。但是,我的功能不是读取我目前拥有的内容。

我在编码方面比较陌生,所以我很抱歉,但我会回答任何问题;

do
{
    printf("\nMax # of characters?\n");
    fflush(stdin);
    scanf("%d", &x);
} while (x < 1 || x > 200);       

do
{

    printf("\nEnter Text:\n");

    enter[i] = getchar();
    i = 1;
    error = 0;

    do
    {
        printf("i = %d\n", (i - 1));
        c = getchar();
        enter[i] = c;
        i++;
    } while (c != '\n');

    if (i > (x + 1))   //<----------- Even though I added one because arrays start at [0]
    {                  //             the program still tells me 'i' (counter) is one 
                       //             more than it should be 

        printf("Words must not be longer than %d letters\n", x);

        printf("You entered %d letters\n", (i - 1)); // -1 to count for the '\n'
        error = 1;
    }

} while (error != 0);


printf("\nOutput: %s\n", enter);

return 0;

【问题讨论】:

  • C 使用基于 0 的数组,因此代码应始终反映这一点。您需要“添加 1”的唯一位置是在 UI 中,因此,在 printf 上执行 I+1 & x+1。
  • 有效ì 的条件是i &lt; x。您没有显示enter 数组的定义,但您必须在输入字符时强制执行该条件,以免数组溢出。 (当您第一次分配 enter[i] = c 时,i 有可能未初始化。)
  • fflush(stdin) 在标准中是明确未定义的行为(尽管在某些实现中受支持,但这不是可移植的)。如果您尝试清除输入流,还有其他方法可用。
  • 人们通常使用forloop 循环进入数组或类似容器,它允许声明一个计数器,指定何时停止循环并像for (int i = 0; c != '\n'; i++)那样递增计数器
  • 您需要在第一次 getchar 调用之前将i 设置为0

标签: c arrays printf


【解决方案1】:

首先你忘记初始化i。第一个

enter[i] = getchar();

是未定义的行为。

其次,i 是数组的索引。如果x 是您允许输入的字符数,则i 应介于0x - 1 之间(包括合法字符)。您还为\n 增加了i,因此合法地i

约束
0 <= i <= x

所以如果i &gt; x 应该打印你的错误信息,而不是i &gt; x + 1


脚注:如果您想知道为什么我们从零开始索引,而任何告诉您我们应该从一开始索引的人都是错误的,那么我只能指出 Edsgar Dijkstra 的权威论文 Why Numbering Should start at Zero

【讨论】:

  • (为什么编号应该从零开始)......以及一个微妙的事实,即从零开始的索引非常适合计算机所说的 binary 以及迭代每个不同数据类型、指针算法和数组定义中的字节数,例如int a[x]; 其中a = &amp;a[0] = &amp;(*(a + 0)) = (a + 0) = a 等等等等(想想用1 而不是0 :) 等价看起来会有多麻烦
猜你喜欢
  • 2013-08-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-06
  • 2012-05-27
相关资源
最近更新 更多