What are the differences between an array of char pointers and a 2D array?

前端 未结 4 1069
一向
一向 2021-01-06 18:38

What are the differences between an array of char pointers and a 2D array?

4条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-06 19:07

    char* pasz[3] = {"abc", "def", "ghi"};
    char asz[3][] = {"abc", "def", "ghi"};
    

    The similarities and differences are basically the same as between these two:

    char *psz = "jkl";
    char sz[] = "jkl";
    

    The first is originally read-only.

    psz[0] = 'a'; // Illegal!!
    

    The second, you can modify, since you allocate it with the [].

    sz[0] = 'b';
    // sz == "bkl"
    

    The first, you can modify what it points to:

    char mysz[] = "abc";
    psz = mysz;
    
    psz[0] = 'b';
    // mysz == "bbc"
    

    The second, you cannot:

    sz = mysz; // Can't assign an array to an array!!
    

提交回复
热议问题