简体   繁体   English

使用指针初始化字符串

[英]Initializing strings using pointers

What is the difference between: 之间有什么区别?

char arr[20]="I am a string"

and

char *arr="I am a string"

How is it possible to initialize an array just by using a pointer? 仅使用指针如何初始化数组?

第一个很清楚,它是一个数组初始化,而第二个意味着字符指针* arr指向未命名的静态数组,该数组将存储字符串“ I is a string”。

One difference is in allocated storage size. 区别在于分配的存储大小。 First expression allocates 20 chars, but the second expression allocate the length of the string (13 chars). 第一个表达式分配20个字符,但是第二个表达式分配字符串的长度(13个字符)。

The second difference is mentioned in this post . 这篇文章中提到了第二个区别。 which is discussed on the way how these variables are allocated. 这些变量如何分配的方式进行了讨论。

In first case you are partially initializing stack allocated array with 14 chars taken from buffer represented by "I am a string" string literal. 在第一种情况下,您将使用从"I am a string"字符串文字表示的缓冲区中提取的14个字符来部分初始化堆栈分配的数组。

In second case you are initializing stack allocated pointer with a pointer to a buffer with static storage duration represented by "I am a string" string literal. 在第二种情况下,将使用指向静态存储持续时间的缓冲区的指针初始化堆栈分配的指针,该缓冲区的静态存储持续时间由"I am a string"字符串文字表示。 Also notice that in second case you should use const char *arr . 还要注意,在第二种情况下,您应该使用const char *arr

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM