的char *数组,字符数组[] [英] char *array and char array[]

查看:172
本文介绍了的char *数组,字符数组[]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我写这个

 的char *数组=一件好事关于音乐;

其实,我创建一个数组?我的意思是这样的一样吗?

 字符数组[] = {一,好,事,左右,音乐};


解决方案

的声明和初始化

 的char *数组=一件好事关于音乐;

声明了一个指针阵列并使其指向包含31个字符常量数组。

的声明和初始化

 字符数组[] =一,好,东西约,乐;

声明字符数组,含有31个字符。

是的,数组的大小为31,因为它包括终止'\\ 0'字符。


在内存中排列,这将是这样的第一个:


------- + + + + ------------------------------
|阵列| - > | 关于音乐的一个好东西|
------- + + + + ------------------------------

和喜欢本作的第二个:


+ ------------------------------ +
| 关于音乐的一个好东西|
+ ------------------------------ +


数组衰变为指针。这意味着,当你,例如,传递一个数组作为参数传递给它作为一个指针传递的功能。

指针和数组的几乎的互换。你不能,例如,使用的sizeof(指针),因为返回实际指针的大小,而不是它所指向。此外,当你如&放大器;指针你得到的指针的地址,但&放大器;阵列返回一个指针数组(这是同样既是阵列&放大器;数组[0]


有关更多的乐趣:正如许多人都知道,这是可以使用数组索引访问指针时。但由于数组衰变为指针,它可以使用与数组一些指针运算。

例如:

 字符数组[] =Foobar的; / *声明的7个字符数组* /

通过上述,您可以访问的第四个元素('B '字符)利用

 数组[3]

  *(阵列+ 3)

而因为除了是交换,最后还可以作为pssed

前$ P $

  *(3 +数组)

这导致了乐趣语法

  3 [阵列]

if I write this

 char *array = "One good thing about music";

I actually create an array? I mean it's the same like this?

char array[] = {"One", "good", "thing", "about", "music"};

解决方案

The declaration and initialization

char *array = "One good thing about music";

declares a pointer array and make it point to a constant array of 31 characters.

The declaration and initialization

char array[] = "One, good, thing, about, music";

declares an array of characters, containing 31 characters.

And yes, the size of the arrays is 31, as it includes the terminating '\0' character.


Laid out in memory, it will be something like this for the first:

+-------+     +------------------------------+
| array | --> | "One good thing about music" |
+-------+     +------------------------------+

And like this for the second:

+------------------------------+
| "One good thing about music" |
+------------------------------+


Arrays decays to pointers. That mean that when you, for example, pass an array as an argument to a function it will be passed as a pointer.

Pointers and arrays are almost interchangeable. You can not, for example, use sizeof(pointer) because that returns the size of the actual pointer and not what it points to. Also when you do e.g. &pointer you get the address of the pointer, but &array returns a pointer to the array (which is the same as both array and &array[0]).


For more fun: As many knows, it's possible to use array indexing when accessing a pointer. But because arrays decays to pointers it's possible to use some pointer arithmetic with arrays.

For example:

char array[] = "Foobar";  /* Declare an array of 7 characters */

With the above, you can access the fourth element (the 'b' character) using either

array[3]

or

*(array + 3)

And because addition is commutative, the last can also be expressed as

*(3 + array)

which leads to the fun syntax

3[array]

这篇关于的char *数组,字符数组[]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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