如何在内联结构体中分配字符数组?
我正在尝试做这样的事情:
struct SomeStruct {
const char *bytes;
const char *desc;
};
SomeStruct example = { { 0x10, 0x11, 0x12, 0x13 }, "10-13" };
为什么这不起作用?
I'm trying to do something like this:
struct SomeStruct {
const char *bytes;
const char *desc;
};
SomeStruct example = { { 0x10, 0x11, 0x12, 0x13 }, "10-13" };
Why isn't this working?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
可能是因为
{ 0x10, 0x11, 0x12, 0x13 }
是一个char
数组,而不是指向char
的指针。尝试使用
SomeStruct example = { "\x10\x11\x12\x13", "10-13" };
代替。Probably because
{ 0x10, 0x11, 0x12, 0x13 }
is an array ofchar
, not a pointer tochar
.Try
SomeStruct example = { "\x10\x11\x12\x13", "10-13" };
instead.因为
{ ... }
语法只适合给数组赋值,而const char*
是指针,而不是数组。如果您将
bytes
声明为数组 -char bytes[4];
- 赋值将会起作用。Because the
{ ... }
syntax is only suitable for assigning arrays, whereasconst char*
is a pointer, not an array.If you declare
bytes
as an array instead –char bytes[4];
– the assignment will work.因为编译器无法将
{1, 2, 3, 4}
转换为指向字节的指针(它可以将“10-13”转换为指向字符的指针)。您可以以“字符串”格式指定字节(如果您不介意
bytes
指向的内存中存在额外的0x00):Because the compiler cannot convert
{1, 2, 3, 4}
to a pointer to bytes (it can convert "10-13" to a pointer to char).You can specify the bytes in 'string' format (if you don't mind an extra 0x00 in the memory pointed to by
bytes
):正如其他人所说,您的初始化序列对于
数组,结构体包含一个指针。您可以使用
maraguida 的响应,使用字符串文字,但恕我直言,这
不是最具可读性的(如果你决定,它就不起作用
用显式常量替换显式常量)。这
更通用的解决方案是定义一个单独的命名数组,并且
使用它:
这适用于任意初始化表达式
字符数组。
As others have said, your initializer sequence is valid for an
array, and the struct contains a pointer. You can use
maraguida's response, using a string literal, but IMHO, this
isn't the most readable (and it won't work if, say, you decide
to replace the explicit constants with manifest constants). The
more general solution is to define a separate, named array, and
use it:
This will work for arbitrary initialization expressions in the
character array.