提问者:小点点

将字符串的一部分分配给字符数组


我有一个固定大小的数组,我想为它分配一个固定文本:

char text[16];
text = "0123456789abcdef";

当然,这是行不通的,因为右手边包含空终止符。

error: incompatible types in assignment of 'const char [17]' to 'char [16]'

文本是可读的,因此我更愿意将其保持为一个片段,即不写{'0','1',。。。}

我能以某种方式完成任务吗?

顺便说一下,我只有几百字节的RAM,所以最好(但仅次于人类可读性要求)解决方案不应该使用两倍的RAM来临时复制或类似的东西。


共3个答案

匿名用户

如果用C:

char text[16];
strncpy(text, "0123456789abcdef", sizeof(text));

请注意,text没有空终止符,并且与strlen等标准C函数不兼容。 如果文本是可读的,我建议包括终结者。 它只是一个字符,但它会使你的生活轻松得多。

示例:

char text[17];
strncpy(text, "0123456789abcdef", sizeof(text));

匿名用户

首先,如果您有任何误解,“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()--使用模板,您可以在编译时告诉数组的大小。 根据您的需要,您可以决定是否实施边界检查。

匿名用户

您犯了两个错误:

>

  • 您试图将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!";