5

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

(请原谅我对结构所做的一切......实际上这段代码应该适合更大的东西,因此该结构及其使用的奇怪之处)

#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 个字符吗?这两个(有时是零,有时是一个)字符来自哪里?

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

4

4 回答 4

2

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

    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);
于 2013-05-30T17:36:51.683 回答
2

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

于 2013-05-30T17:37:57.253 回答
2

里面没有空字符segment_listing

于 2013-05-30T17:38:00.120 回答
-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};
于 2013-05-30T17:46:19.183 回答