c - 关于我在网上找到的数组示例的更多解释

标签 c arrays

我刚刚开始学习 C 语言程序,并试图了解数组。我在网上找到了这个例子,但不明白它是如何工作的。这是代码:

#include <stdio.h>

int main () {

   int n[ 10 ]; /* n is an array of 10 integers */
   int i,j;

   /* initialize elements of array n to 0 */         
   for ( i = 0; i < 10; i++ ) {
      n[ i ] = i + 100; /* set element at location i to i + 100 */
   }

   /* output each array element's value */
   for (j = 0; j < 10; j++ ) {
      printf("Element[%d] = %d\n", j, n[j] );
   }

   return 0;
}

我在这里不明白的是 int j 如何链接到 int i。在输出中,在 printf 行,我不明白为什么它不是:

printf("Element[%d] = %d\n", i, n[i]);

为什么我们需要另一个 int j ?

我不明白的另一件事是该行中的 %d。为什么是 %d 而不是 %i? d 还没有在任何地方声明过吗?

任何比我发现此示例的网站更深入的解释将不胜感激。谢谢。

最佳答案

Why do we need another int j?

你不知道。我假设作者只是在演示您可以使用任何变量来索引数组,只要该变量具有正确的类型(几乎任何整数类型)并保存在正确范围内的值。

数组索引可以是任何整型表达式,无论是整型常量 (a[5])、变量 (a[i]a[ j]),或更复杂的表达式(a[i+j]a[foo(i)]a[1+ j*k/2] 等)。重要的是表达式具有整数类型,并且其结果在正确的范围内(0N-1,其中 N > 是数组中元素的总数)。

And another thing I don't understand is the %d's in that line. Why %d and not %i? d hasn't been declared anywhere right?

%d 是一个转换说明符 - 它与任何变量无关,并且不需要单独声明。格式字符串中的转换说明符告诉 printf 附加参数的数量和类型,以及如何设置这些值的显示格式。

在行

printf("Element[%d] = %d\n", i, n[i]);

格式字符串中的 %d 说明符告诉 printf in[i] 都具有类型 int,并且它们将被格式化为十进制整数(例如,而不是十六进制或八进制)。

以下是转换说明符的不完整列表:

Specifier        Argument Type        Output format
---------        -------------        -------------
    %d,%i                  int        decimal integer
       %u         unsigned int        decimal integer (non-negative)
       %f               double        decimal floating point
    %x,%X         unsigned int        hexadecimal integer (non-negative)
       %o         unsigned int        octal (non-negative)
       %c                 char        single character
       %s               char *        text

查看您方便的 C 引用手册以获取完整列表。如果您没有方便的 C 引用手册,我推荐 Harbison & Steele 的 C: A Reference Manual

关于c - 关于我在网上找到的数组示例的更多解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41940890/

相关文章:

c - 如何定义Type A中的Type A和Type A中的Type B?

PHP - 按另一个数组的值对关联数组进行排序

javascript - 从 JSON 数组中获取数据

c - 使用 CUDA 在本地内存中定义数组的可变大小

通过引用传递参数时在汇编器 x86 中实现的 C 函数

c - Linux 内核模块中的 trunc() 和 ftrunc() 等效项

c++ - 从真值的 STL vector 中随机选择索引

java - 如何创建等于某个值的整数数组?

javascript - jQuery Push/Join 不存储在空数组中

c - 模型 LARGE 中的组件,我需要发送到 malloc#c