C语言基础 -26 数组_ 二维数组定义/存储方式

二维数组的存储是按行存储,先存第一行,存完后再存储第二行。二位数组仍然是连续的一片存储空间,其中数组名代表数组的开头,a[0][0]

[root@localhost CH01]# cat arr_2d.c
#include<stdio.h>
#include<stdlib.h>
#define M 2
#define N 3

int main()
{
        int a[M][N];
        int i,j;

        for(i = 0; i < M; i++)
        {
                for(j = 0; j < N; j++)
                {
                        printf("%d",a[i][j]);
                }
                printf("\n");
        }
exit(0);
}

[root@localhost CH01]# make arr_2d
cc     arr_2d.c   -o arr_2d
[root@localhost CH01]# ./arr_2d  //由于是auto类型,未赋值时,输出随机
419588804195536
0-169986624032764
[root@localhost CH01]# cat arr_2d.c
#include<stdio.h>
#include<stdlib.h>
#define M 2
#define N 3

int main()
{
        int a[M][N];
        int i,j;

        for(i = 0; i < M; i++)
        {
                for(j = 0; j < N; j++)
                {
                        scanf("%d",&a[i][j]);
                }
        }

        for(i = 0; i < M; i++)
        {
                for(j = 0; j < N; j++)
                {
                        printf("%d",a[i][j]);
                }
                printf("\n");
        }
exit(0);
}


[root@localhost CH01]# make arr_2d 
cc     arr_2d.c   -o arr_2d
[root@localhost CH01]# ./arr_2d
1
2
3
4
5
6
123
456

标准赋值

 a[M][N] = {{1,2,3},{4,5,6}};

部分元素初始化,余下的元素全部填0

[root@localhost CH01]# cat arr_2d.c
#include<stdio.h>
#include<stdlib.h>
#define M 2
#define N 3

int main()
{
        int a[M][N] = {{1,2,3},{4,5,6}};
        int i,j;
/*
        for(i = 0; i < M; i++)
        {
                for(j = 0; j < N; j++)
                {
                        scanf("%d",&a[i][j]);
                }
        }
*/
        for(i = 0; i < M; i++)
        {
                for(j = 0; j < N; j++)
                {
                        printf("a[%d][%d]`s address is %p\n",i,j,&a[i][j]);
                }
        }
exit(0);
}


[root@localhost CH01]# make arr_2d 
cc     arr_2d.c   -o arr_2d
[root@localhost CH01]# ./arr_2d    
a[0][0]`s address is 0x7ffd10ef5800
a[0][1]`s address is 0x7ffd10ef5804
a[0][2]`s address is 0x7ffd10ef5808
a[1][0]`s address is 0x7ffd10ef580c
a[1][1]`s address is 0x7ffd10ef5810
a[1][2]`s address is 0x7ffd10ef5814

发现,二维数组的地址仍然是连续存放

猜你喜欢

转载自blog.csdn.net/f2157120/article/details/106738303
今日推荐