c 语言定义二维数组
时间: 2023-09-21 08:06:24 浏览: 346
在 C 语言中,可以通过以下语法定义一个二维数组:
```c
data_type array_name[row_size][column_size];
```
其中,`data_type` 表示数组元素的数据类型,`array_name` 是数组的名称,`row_size` 表示数组的行数,`column_size` 表示数组的列数。
例如,下面的语句定义了一个大小为 3x4 的二维数组:
```c
int matrix[3][4];
```
这个二维数组可以用来存储 3 行 4 列的整数矩阵。注意,C 语言中的数组下标从 0 开始,因此访问数组元素时需要使用下标值 0 到 row_size-1 或者 0 到 column_size-1。
相关问题
用c 语言随机二维数组生成迷宫
好的,生成迷宫可以使用随机生成的二维数组,其中0表示墙壁,1表示通路。以下是一个简单的C语言程序示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define ROW 10 // 迷宫的行数
#define COL 20 // 迷宫的列数
int maze[ROW][COL]; // 定义迷宫数组
void init_maze() {
// 初始化迷宫数组,设置所有元素为0
for (int i = 0; i < ROW; i++) {
for (int j = 0; j < COL; j++) {
maze[i][j] = 0;
}
}
}
void print_maze() {
// 输出迷宫数组
for (int i = 0; i < ROW; i++) {
for (int j = 0; j < COL; j++) {
printf("%d ", maze[i][j]);
}
printf("\n");
}
}
void generate_maze() {
// 随机生成迷宫
srand(time(NULL)); // 设置随机种子
for (int i = 0; i < ROW; i++) {
for (int j = 0; j < COL; j++) {
if (i == 0 || j == 0 || i == ROW - 1 || j == COL - 1) {
maze[i][j] = 0; // 边界为墙壁
} else {
maze[i][j] = rand() % 2; // 随机生成0或1
}
}
}
}
int main() {
init_maze(); // 初始化迷宫
generate_maze(); // 生成迷宫
print_maze(); // 输出迷宫
return 0;
}
```
该程序生成一个10行20列的随机迷宫,其中边界为墙壁。你可以根据需要修改迷宫的大小和边界条件。
c++语言二维数组输入
下面是 C++ 中二维数组的输入示例:
```c++
#include <iostream>
using namespace std;
int main() {
int arr[3][3];
// 输入二维数组
for(int i=0; i<3; i++) {
for(int j=0; j<3; j++) {
cin >> arr[i][j];
}
}
// 输出二维数组
for(int i=0; i<3; i++) {
for(int j=0; j<3; j++) {
cout << arr[i][j] << " ";
}
cout << endl;
}
return 0;
}
```
在上面的示例中,我们定义了一个 `3x3` 的整型数组 `arr`,然后使用两个嵌套的循环语句来逐个输入数组中的元素。最后,我们再使用两个嵌套的循环语句来输出数组中的元素。
阅读全文
相关推荐













