如何在不使用循环的情况下在 C 中初始化 N 维数组 [英] How to initialize N dimensional arrays in C without using loop

查看:44
本文介绍了如何在不使用循环的情况下在 C 中初始化 N 维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想初始化一个 3 x 3 矩阵,前两行为 0,最后一行为 1.我已经声明了一个二维数组 int matrix[3][3]

I want to initalize a 3 x 3 matrix with first two rows as 0's and last row as 1's. I have declared a 2D array int matrix[3][3]

我想在不使用循环的情况下初始化它,如下所示

I want to initialize it without using loops as shown below

0 0 0
0 0 0
1 1 1

0 0 0
0 0 0
1 1 1

我也想要一个 N 维数组的解决方案

I would also like a solution for N dimiensional array

推荐答案

int matrix[3][3] = {
    { 0, 0, 0 },
    { 0, 0, 0 },
    { 1, 1, 1 }
};

或者,更紧凑:

int matrix[3][3] = {
    [2] = { 1, 1, 1 }
};

只要 N 是固定的,该解决方案就适用于 N.如果 N 很大,您可以使用 mouviciel 对 的回答这个问题.

The solution generalizes for N so long as N is fixed. If N is large, you can use mouviciel's answer to this question.

这篇关于如何在不使用循环的情况下在 C 中初始化 N 维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆