初始化一个 Char*[]
标题中的问题是,如何在 C++ 中初始化 char*[] 并为其赋值,谢谢。
Question is in the title, how do I initialize a char*[] and give values to it in C++, thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
尽管您可能知道, char*[] 是一个指向字符的指针数组,我猜您想存储多个字符串。初始化此类指针的数组非常简单:
...或者如果您在堆栈上分配内存:
那么您可能希望用循环填充该数组,例如:
正如此答案的注释中所述,如果您正在使用新的(动态分配)分配数组,请记住使用以下命令删除数组:
Though you're probably aware, char*[] is an array of pointers to characters, and I would guess you want to store a number of strings. Initializing an array of such pointers is as simple as:
...or if you're allocating memory on the stack:
You would then probably want to fill the array with a loop such as:
As noted in the comments for this answer, if you're allocating the array with new (dynamic allocation) remember to delete your array with:
根据您想要初始化的内容,您可以执行以下任一操作:
等等。
Depending on what you want to initialize to you could do any of:
etc. etc.
我注意到你必须小心的一件事...C 和 C++ 在初始化语法上有些不同。正如 Mark B. 上面指出的,您可以这样初始化一个 char 指针数组:
但是在 C++ 中。正如 kriss 指出的那样,这会向您发出有关从 string 到 char* 的已弃用转换的警告。这是因为 C++ 假设您希望使用字符串来表示字符串 ;-}。
这并不总是正确的。因此,当您确实想要初始化 char* 数组时,我发现我必须这样做:
编译器现在很高兴......
One thing I have noticed that you must be careful of... C and C++ have diverged a bit in initialization syntax. As Mark B. points out above, you can initialize an array of char pointers thusly:
But in C++. as kriss points out, this nets you a warning about a deprecated conversion from string to char*. That's because C++ assumes you'll want to use strings for strings ;-}.
That's not always true. So when you really do want to initialize an array of char*, I have found that I have to do it like so:
The compiler is now happy...
像这样:
Like this:
如果您确实只想要一个 C 风格的常量字符串数组(例如索引消息):
但是,如果您尝试维护运行时变量字符串的容器,请使用 C++ 工具
std::vector
将使跟踪所有内存操作变得更加容易。If you really just want a C-style array of constant strings (for example indexed messages):
If however you're trying to maintain a container of runtime variable strings, using the C++ facility
std::vector<std::string>
will make keeping track of all the memory operations much easier.就像这样:
但不知怎的,我相信这不是真正问题的答案...
我想要一个在编译时定义的 C 字符串数组,你应该使用 const char * 数组代替:
如果没有 const 我的编译器会说:
警告:不推荐从字符串常量到“char*”的转换
Like that:
But somehow I believe that's not the answer to the real question...
I you want an array of C strings defined at compile time you should use an array of const char * instead:
Without the const my compiler would say :
warning: deprecated conversion from string constant to ‘char*’
就像任何其他数组一样:
Just like any other array: