C语言中用二维数组定义的字符串数组与用指针数组定义的字符串数组的解析与归纳

1.char a[n][m]:

a. a是一个内含n个数组的数组,每个数组的大小为m字节,于是在内存中a占用了(n*m)个字节的空间
b. 数组名a具有地址含义,指向第一个拥有m个字符元素数组

 注意:此时如果给a赋值,那么字符串的长度不能超过m-1

c. 和数组形式定义的字符串相同,数组形式定义的字符串数组,存储了字符串字面量的副本,可以直接对这些字符串进行更改
d. 其中每个含有m个元素的数组必须不大不小的将数组填满,如果字符串长度小于m-1,其余位置就补’\0’。
e. ps:在初始化时,m绝对不能缺省,n可以缺省

2.const char *a[m]—(const可省略)

a. a是一个内含m个指针的数组(指针就是地址)在我的电脑中,每个地址用8个字节来储存,a在计算机中占据了8m个字节的空间
b. 这表示a[i]是一个指针,指向第i个字符串
c. a[2][1]表示指针所指的第3个字符串中的第2个字符元素
d. 和指针形式定义的字符串相同,指针形式定义的字符串数组,其中的字符串字面量存储在静态存储区,所以不可以更改
e. 每一个字符串并没有固定的长度,甚至不同的字符串不必存储在连续的内存空间中

3.程序示例

/*探究指针数组和字符串数组的区别与联系*/
#include <stdio.h>
#define SLEN 40
#define LIM 5

int main()
{
    
    
    /*指针数组定义字符串*/
    /*这是一个内含5个指针的数组*/
    const char *mytalents[] = {
    
    
        "Adding number swiftly",
        "Multipling accurately",
        "Stashing data",
        "Following instructions to the letter",
        "Understanding the C language"};
    /*字符串数组*/
    /*内含5个数组的数组,每个数组的大小为40*/
    char yourtalents[LIM][SLEN] = {
    
    
        "Walking in a straight line",
        "Sleeping",
        "Watching television",
        "Mailing letters",
        "Reading email"};

    int i;
    puts("Lets compare talents.");

    /*%-36s的意思(推测)是之后要打印的字符串共占据36个字符位;有-代表先打印字符再打印空格,没有-则表示先打印空格再打印字符*/
    printf("%-36s %-25s\n", "My Talents", "Your Talents");

    for (i = 0; i < LIM; i++)
    {
    
    
        printf("%-36s %-25s\n", mytalents[i], yourtalents[i]);
    }
    printf("\nsizeof mytalents:%lld, sizeof yourtalents: %lld\n", sizeof(mytalents), sizeof(yourtalents));
    return 0;
}
程序输出:
Lets compare talents.
My Talents                           Your Talents
Adding number swiftly                Walking in a straight line
Multipling accurately                Sleeping
Stashing data                        Watching television
Following instructions to the letter Mailing letters
Understanding the C language         Reading email

sizeof mytalents:40, sizeof yourtalents: 200

猜你喜欢

转载自blog.csdn.net/qq_40459977/article/details/106937412
今日推荐