简体   繁体   English

从字符串到字符数组的转换如何在 C++ 中工作?

[英]How does conversion from string to char array work in C++?

I just started learning C++ and I was trying to output a string through printf.我刚开始学习 C++,我试图通过 printf 来 output 字符串。 It wouldn't work because I had to convert the string into a char array first.它不起作用,因为我必须先将字符串转换为 char 数组。 I googled it and it seems that the best solution was this:我用谷歌搜索了一下,似乎最好的解决方案是:

char *a = &b[0];

I somewhat understand it: It's getting a reference to the first character and setting a to that.我有点理解:它引用了第一个字符并将 a 设置为该字符。 The part that I don't understand is that this only makes sense to me if the string is stored on the stack, which I know it sometimes can be.我不明白的部分是,如果字符串存储在堆栈中,这对我来说才有意义,我知道有时可以。 If the string is on the heap, what exactly will the [0] index return?如果字符串在堆上,那么 [0] 索引究竟会返回什么? Does it return the pointer to the first index, because then the & isn't necessary is it?它是否将指针返回到第一个索引,因为 & 不是必需的吗? If it returns the character, doesn't that character take the form of a single value on the stack, which, when referenced, wouldn't give you the correct char array?如果它返回字符,该字符不是采用堆栈上的单个值的形式,当被引用时,它不会给你正确的 char 数组?

The thing to note is that operator[] returns a reference .需要注意的是operator[]返回一个引用

cppreference : 参考

reference operator[]( size_type pos );参考运算符[]( size_type pos );

Returns a reference to the character at specified location pos.返回对指定位置 pos 的字符的引用。

This is important because it means that b[0] is essentially an alias to the first character in the string.这很重要,因为这意味着b[0]本质上是字符串中第一个字符的别名。 Taking its address will then give you a pointer to the underlying buffer the string's data is stored in. It doesn't matter where it is (stack, heap, etc).然后,获取它的地址将为您提供一个指向存储字符串数据的底层缓冲区的指针。它在哪里(堆栈、堆等)并不重要。 This is also what lets you modify the string's data by using eg b[0] = 'a';这也是让您可以使用例如b[0] = 'a';来修改字符串数据的原因。 . .

Note that you can also use c_str() and data() to get a pointer to the first character in the string.请注意,您还可以使用c_str()data()来获取指向字符串中第一个字符的指针。 Since C++17 data() can return a non-const pointer.由于 C++17 data()可以返回非常量指针。

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

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