在c++中正确使用memset和memcpy初始化字符数组

Using memset and memcpy correctly to initialize a character array in C++

本文关键字:memcpy 初始化 字符 数组 memset c++      更新时间:2023-10-16

我想用字符指针中的数据初始化一个字符数组。我为此编写了以下代码:

(请原谅我正在做的结构和所有…实际上,这段代码应该适合更大的代码,因此这个结构和它的使用是奇怪的)

#include <iostream>
#include <string>
struct ABC 
{
    char a;
    char b;
    char c[16];
};
int main(int argc, char const *argv[])
{
    struct ABC** abc;
    std::string _r = "Ritwik";
    const char* r = _r.c_str();
    if (_r.length() <= sizeof((*abc)->c))
    {
        int padding = sizeof((*abc)->c) - _r.length();
        std::cout<<"Size of `c` variable is : "<<sizeof((*abc)->c)<<std::endl;
        std::cout<<"Value of padding is calculated to be : "<<padding<<std::endl;
        char segment_listing[ sizeof((*abc)->c)]; 
        std::cout<<"sizeof segment_listing is "<<sizeof(segment_listing)<<std::endl;
        memcpy(segment_listing, r, _r.length());
        memset( (segment_listing + _r.length()), ' ', padding);
        std::cout<<segment_listing<<std::endl;
    }
    return 0;
}

然而,当我运行我的代码时,我在字符串的末尾得到这些奇怪的字符:

(rh4dev01:~/rough) rghosh> ./crptr
Size of `c` variable is : 16
Value of padding is calculated to be : 10
sizeof segment_listing is 16
Ritwik          °×
(rh4dev01:~/rough) rghosh> ./crptr
Size of `c` variable is : 16
Value of padding is calculated to be : 10
sizeof segment_listing is 16
Ritwik           Ñ
(rh4dev01:~/rough) rghosh> ./crptr
Size of `c` variable is : 16
Value of padding is calculated to be : 10
sizeof segment_listing is 16
Ritwik          g
(rh4dev01:~/rough) rghosh> ./crptr
Size of `c` variable is : 16
Value of padding is calculated to be : 10
sizeof segment_listing is 16
Ritwik          pô
(rh4dev01:~/rough) rghosh> ./crptr
Size of `c` variable is : 16
Value of padding is calculated to be : 10
sizeof segment_listing is 16
Ritwik
(rh4dev01:~/rough) rghosh> ./crptr
Size of `c` variable is : 16
Value of padding is calculated to be : 10
sizeof segment_listing is 16
Ritwik          àå
(rh4dev01:~/rough) rghosh> ./crptr
Size of `c` variable is : 16
Value of padding is calculated to be : 10
sizeof segment_listing is 16
Ritwik           »
(rh4dev01:~/rough) rghosh> ./crptr
Size of `c` variable is : 16
Value of padding is calculated to be : 10
sizeof segment_listing is 16
Ritwik          pZ

你能解释一下为什么会这样吗?既然我只打印一个长度只有16个字符的字符数组,不应该只打印16个字符吗?这两个字符(有时是0,有时是1)是从哪里来的?

更重要的是,我是否通过填充破坏了任何内存(不属于我的字符数组c) ?

您的字符串需要以NUL终止。

    memcpy(segment_listing, r, _r.length());
    memset( (segment_listing + _r.length()), ' ', padding-1);
    segment_listing[_r.length() + padding - 1] = '';

也许您使用snprintf()会更好,它将为您添加终止符:

    snprintf(segment_listing, sizeof(segment_listing), "%-*s",
             (int)sizeof(segment_listing)-1, r);

C字符串以0字节结束,您没有在任何地方考虑到这一点。您需要以值0结束字符串,并且必须在所有计算中考虑额外的字节。

segment_listing中没有null字符

const int SIZE = 16;  //or 17 if you want 16 + null char
//pre-initialise array - then will automatically be null terminated
char segment_listing[SIZE] = {0};