编辑:问完这个问题后,我被告知有关问题How to initialize a char array without the null terminator?的内容几乎是相同的。 (我也在构建网络数据包。)
无论如何,我还是会公开这个问题,因为我只是在分配而不是初始化。
我有一个固定大小的数组,我想为其分配一个固定文本:
char text[16];
text = "0123456789abcdef";
当然这是行不通的,因为右侧包含空终止符。
error: incompatible types in assignment of 'const char [17]' to 'char [16]'
该文本是人类可读的,因此我宁愿将其合而为一,即不要写{'0', '1', ...}
。
我可以以某种方式使作业正常工作吗?
顺便说一下,我只有几百个字节的RAM,因此最好(对于人类可读性要求仅次于该解决方案)该解决方案不应将RAM用作临时副本或类似内容的两倍。
答案 0 :(得分:2)
如果您使用C编写:
char text[16];
strncpy(text, "0123456789abcdef", sizeof(text));
请注意,text
将没有空终止符,并且与strlen
之类的标准C函数不兼容。如果文字易于阅读,建议添加终结符。它只是一个角色,但是它将使您的生活更加轻松。
示例:
char text[17];
strncpy(text, "0123456789abcdef", sizeof(text));
答案 1 :(得分:0)
首先,如果您有任何误解-"0123456789abcdef"
是字符串文字。其类型为const char [17]
,而不是const char [16]
,因为此字符串文字的末尾有一个空终止符\0
。
然后,我假设您的意思是分配而不是初始化。他们是不同的。
我可以想到多种分配方法。您可以根据需要选择。
#include <cstddef>
#include <cstring>
#include <iostream>
#include <string>
#include <string_view>
using std::size_t;
template<size_t N>
void print(const char (&a)[N])
{
for (size_t i = 0; i != N; ++i)
putchar(a[i]);
putchar('\n');
}
void foo1()
{
char text[16];
std::memcpy(text, "0123456789abcdef", sizeof text);
print(text);
}
void foo2()
{
char text[16];
std::string("0123456789abcdef").copy(text, sizeof text);
print(text);
}
void foo3()
{
char text[16];
std::string_view("0123456789abcdef").copy(text, sizeof text);
print(text);
}
// programmer needs to make sure access with src is valid
template<size_t N>
void assign(char (& dest)[N], const char * src)
{
for (size_t i = 0; i != N; ++i)
dest[i] = *src++;
}
void foo4()
{
char text[16];
assign(text, "0123456789abcdef");
print(text);
}
int main()
{
foo1(); // 0123456789abcdef
foo2(); // 0123456789abcdef
foo3(); // 0123456789abcdef
foo4(); // 0123456789abcdef
return 0;
}
一些评论:
std::memcpy
是C语言的传统内存复制方式std::string_view
是字符串的轻量级视图,是C ++ 17中引入的assign()
-使用模板,您可以在编译时确定数组的大小。根据您的需要,您可以决定是否实施边界检查。答案 2 :(得分:-1)
您犯了两个错误:
您试图将17个字节的数据保存到只能容纳16个元素的数组中。
即使更正了第一个错误,分配方法也不正确。
1。声明后分配:
char str[MAX];
str = "test"; // error
2。初始化期间的放置长度:
char str[10] = "something"; // trying to insert 'something' INTO the 10th index
// not TILL the 10th index
1。在同一行中声明时进行初始化:
char str[] = "hello world, how are you?";
2。指针的使用:
char *str = new char[MAX]; // MAX is a user defined 'const int'
strcpy(str, "hello"); // assuming MAX >=6
作为旁注:您正在使用C ++,您可以使用std::string
以与尝试相同的方式执行相同的操作:
std::string str;
str = "hello!";