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

时间:2013-05-30 17:31:09

标签: c++ c memory-management

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

(请原谅我正在使用的结构和所有..实际上这个代码应该适合更大的东西,因此该结构的奇怪性及其使用)

#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

你能解释一下为什么会这样吗?由于我只打印一个字符数组taht只有16个字符,不应该只打印16个字符?这两个(有时是零,有时是一个)角色来自哪里?

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

4 个答案:

答案 0 :(得分:2)

您的字符串需要以NULL结尾。

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

使用snprintf()可能会更好地为您提供服务,这将为您添加终结符:

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

答案 1 :(得分:2)

C字符串以0字节终止,您无法在任何地方进行说明。 您需要使用值0终止字符串,并且在所有计算中都必须在帐户中使用该额外字节。

答案 2 :(得分:2)

segment_listing

中没有空字符

答案 3 :(得分:-1)

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};