【问题标题】:Can you use double brackets in a nested for loop?你可以在嵌套的 for 循环中使用双括号吗?
【发布时间】:2015-05-19 03:39:54
【问题描述】:

我的问题的意思是,如果我有一个像

这样的嵌套 for 循环
for(int i = 0; i < 10; i++)
{
    for(int j = 0; j < 10; i++)
    {
        printf("%d\n"___);
    } 
}

我会在空白处填什么?如果我已经声明了一个数组,[i][j] 会是非法的吗?

【问题讨论】:

  • printf("%d\n"[i][j]); 是非法的,这个事实与 for 循环无关。
  • 不,假设数组被声明为 int arrayName[x][y]; 其中 x 和 y 至少为 10,这没有错
  • @asimes: ...并假设他想写printf("%d\n", arrayName[i][j]),而不是immibis评论中的printf("%d\n"[i][j])。
  • @Amadan,我希望他不打算像 immibis 建议的那样写...
  • @AlanAu 实际上,在 C 中,通常不是。

标签: c for-loop nested-loops


【解决方案1】:

根据你的问题,我不确定你到底坚持了什么,所以我用 cmets 做了一个最小的 C 程序

我声明了一个 int 数组,它的第一维和第二维至少为 10,因为您将 i 和 j 从 0 迭代到 9(含)。这是为了避免迭代时出现越界问题

数组的元素没有在程序中初始化。当你运行这个程序时,它可能会打印全零。也有可能打印出其他碰巧在内存中的值(因为数组值没有初始化)

最后我在 for 循环之外声明了 i 和 j 以防万一这是您面临的问题

#include <stdio.h>

int main(int argc, char** argv) {
    // Declare an array
    // Note that both dimensions are at least 10
    // Also note that none of the values are initialized here
    int myArray[10][10];

    // Both i and j are declared here rather than in the for loop
    // This is to avoid the following potential error:
    // error: 'for' loop initial declarations are only allowed in C99 or C11 mode
    int i, j;

    for (i = 0; i < 10; i++) {
        for (j = 0; j < 10; j++) {
            // Note that the values this prints are uninitialized
            printf("%d\n", myArray[i][j]);
        }
    }

    return 0;
}

【讨论】:

    【解决方案2】:

    您的问题确实不清楚。但据我了解,您有一些二维数组,并且您想打印数组的内容。

    你必须已经将arrary定义为int arr[10][10],然后你才能使用,

    printf("%d\n", arr[i][j]);
    

    【讨论】:

    • 更正您的答案...您说声明 arr 并且您正在打印 a 并且也没有逗号
    • @asimes 已更正。谢谢。
    猜你喜欢
    • 2010-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多