"char * var [3]"和"char * var [3]"之间有什么区别?和"char var [3] [15]"? [英] What is the difference between "char *var[3]" and "char var[3][15]"?

查看:63
本文介绍了"char * var [3]"和"char * var [3]"之间有什么区别?和"char var [3] [15]"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对以下两种方法感到困惑:

I am confused between the following two ways:

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.

  1. 它们之间有什么区别?
  2. 使用那个或那个的情况是什么?

推荐答案

有两种类型的二维数组,并且在这两种类型中都有.

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]"之间有什么区别?和"char var [3] [15]"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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