我有很大的困惑来理解`char * var [3]`,`char var [3] [15]`的区别 [英] I have big confusion to understand the difference between `char *var[3]`, `char var[3][15]`

查看:168
本文介绍了我有很大的困惑来理解`char * var [3]`,`char var [3] [15]`的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

与标题一样。

我感到困惑。

char var[3][15]= {"Hello_world!", "good", "bad"}; // as known this is for an 2D array.  
char *var[3]= {"Hello_world!", "good", "bad"}; // and this I think also 2D array, but how.

它们之间有什么区别?

对不起,但我之间有很大的混乱。

I'm sorry but I have big confusion between them.

推荐答案

有两种类型的二维数组,你有两种类型。

There's two types of two dimensional arrays, and you have both types there.

第一个,它是一个5 char [15] 对象的数组,记忆。每个行末尾的未使用字节(在特定情况下但不总是)用零填充。这是大多数人想到的,当你说一个二维数组,但有些人称之为方形数组,以区别于其他类型。

With the first one, it's an array of 5 char[15] objects, which are layed out sequentially in memory. Unused bytes in the end of each "row" are (in your particular case but not always) filled with zeros. This is what most people think of when you say a "two dimensional array", but some people call it a "square" array to distinguish it from the other type. When you initialize it, the string literals are copied into the array directly.

[0][ 0] = 'H'
[0][ 1] = 'e'
...
[0][14] = '\0' (end of each row is filled with zeros)
[1][ 0] = 'G'
[1][ 1] = 'o'
...
[3][13] = '\0' (end of each row is filled with zeros)
[3][14] = '\0' (end of each row is filled with zeros)

第二个是5 char * (指针)的数组,通常数组 char 不必具有相同大小的对象。如果它们指向char对象的数组,则可以作为二维数组访问。由于每个阵列的长度可以是不同的大小,因此这被称为锯齿状阵列。在您的代码中,有三个行,第一个是13个字符长,第二个是5个字符长,第三个是4个字符长。数组的第一个索引在存储器中是顺序的,但是形成内部索引的数组可以在存储器中的任何地方。当初始化它时,这形成一个指向实际字符串字面量的一维数组。它们一起形成一个二维数组。

The second one is an array of 5 char* (pointers) which usually refers to an array of char objects that do not have to be the same size. If they do point at arrays of char objects, this can be accessed as a two dimensional array. Since the length of each array may be a different size, this is referred to as a "jagged array". In your code, there's three "rows", the first is 13 chars long, the second is 5 chars long, and the third is 4 chars long. The first index of the array is sequential in memory, but arrays forming the "inner" index can be anywhere in memory. When you initialize it, this forms a one-dimensional array that points at the actual string literals. Together, they form a two-dimensional array.

[0] -> "Hello_world!"
[1] --------------------------------->"good"
[2] ---------------------->"bad"

这篇关于我有很大的困惑来理解`char * var [3]`,`char var [3] [15]`的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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